数据库另一个文章的、点击进入
目录结构如图所示
pow.xml的配置、 点击进入
使用注解方式,不需要创建Mapper.xml, 忘了删除了...
package cn.lacknb.beans;
public class User {
private String uname;
private String usex;
private Integer uid;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
@Override
public String toString() {
return "User{" +
"uname='" + uname + '\'' +
", usex='" + usex + '\'' +
", uid=" + uid +
'}';
}
}
package cn.lacknb.dao;
import cn.lacknb.beans.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface IUserDao {
@Select("select * from user")
List<User> findAll();
}
package cn.lacknb.mybatis02;
import cn.lacknb.beans.User;
import cn.lacknb.dao.IUserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MapperTest {
public static void main(String[] args) throws IOException {
// 读取配置文件
InputStream config = Resources.getResourceAsStream("com/config/xml/mybatis-config.xml");
// 创建SqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(config);
// 使用工厂类生产SqlSession对象
SqlSession session = factory.openSession();
// 使用Sqlsession创建Dao接口的代理对象
IUserDao dao = session.getMapper(IUserDao.class);
// 使用代理对象执行方法
List<User> users = dao.findAll();
for (User user: users){
System.out.println(user);
}
session.close();
config.close();
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置环境-->
<environments default="development">
<!-- 配置mysql的环境, 和default保持一致-->
<environment id="development">
<!-- 配置事务的类型 JDBC -->
<transactionManager type="JDBC"/>
<!-- 配置数据源(连接池)-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射文件的位置-->
<!-- <mapper resource="com/config/xml/Mapper.xml"/>-->
<!-- 使用注解的方式-->
<mapper class="cn.lacknb.dao.IUserDao"/>
</mappers>
</configuration>
# global logging configuration
log4j.rootLogger=ERROR, stdout
# Mybatis logging configuration...
# 将包com.mybatis下的日志等级设为DEBUG
log4j.logger.com.mybatis=DEBUG
# Console output ...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n