1.搭建Mybatis框架环境
IDE:IntelliJ IDEA 2020.1.1
依赖管理:Maven3.6.1
持久层框架:mybatis3.5.2
数据库:mysql8.0.23
单元测试:junit4.11
mysql连接驱动:mysql-connector-java8.0.25
步骤:
1.创建普通maven项目,在pom.xml中配置junit,mysql-connector-java的jar包依赖
2.参考mybatis官方文档搭建mybatis环境
1.在pom.xml中添加mybatis的依赖
2.在src/main/resources下添加mybatis-config.xml,它是 MyBatis 系统的核心设置,包括数据库连接参数设置和Mapper映射的注册
3.为每一个pojomapper接口配置对应的pojomapper.xml,这个XML相当于该接口的实现,即使用XML文件实现DataAccessObject。
3.实现一个工具类mybatisutils,功能是将mybatis-config.xml----->InputStream ----->SqlSessionFactory
3.在pojo层中实现一个user实体类,对应数据库中的user表
4.在dao层中实现数据表到实体类的映射,接口为UserMapper,使用UserMapper.xml文件实现该接口,要注意在mybatis-config.xml中注册该XML的映射。
5.单元测试:先利用MybatisUtils获得SqlSession,再利用反射获得UserMapper的实例mapper,调用mapper的成员方法获得User对象的List,最后遍历打印所有对象。
数据库中的user表
被映射出来的user对象
2.重要配置文件
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
UserMapper接口对应的UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.UserMapper">
<select id="getUserList" resultType="pojo.User">
select * from mybatis.user
</select>
</mapper>
MybatisUtils.java
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
UserMapperTest.java
public class UserMapperTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user :
userList) {
System.out.println(user);
}
sqlSession.close();
}
}
3.常见问题
Error:java:程序包org.apache.ibatis.io不存在