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>
namespace:实体映射接口的全类名 id:实体映射接口中的方法名 resultType:实体映射接口中的方法的返回参数 parameterType:方法的参数类型 注意:可以将UserMapper与UserMapper.xml分离,即将UserMapper.xml放到resource下与UserMapper有相同包结构下。 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不存在 解决方法
4.优化
连接数据库的配置单独放在一个properties文件中 1.在mybati-congfig.xml同目录下建立db.properties 2.在mybati-congfig.xml的configuration标签内引入db.properties 3.mybati-congfig.xml中value属性值引用db.properties配置文件中配置的值 注意:在mybaties-config.xml中url中&要使用转义符amp;,而在db.properties则不需要。 db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=123456
mybaties-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>
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
MybatiesUtils优化 一级优化
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
InputStream inputStream = null;
try {
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static SqlSession openSqlSession() {
return sqlSessionFactory.openSession();
}
public static void commitAndClose(SqlSession sqlSession) {
if (sqlSession != null) {
sqlSession.commit();
sqlSession.close();
}
}
public static void rollbackAndClose(SqlSession sqlSession) {
if (sqlSession != null) {
sqlSession.rollback();
sqlSession.close();
}
}
}
二级优化
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
InputStream inputStream = null;
try {
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
public static SqlSession openSqlSession() {
SqlSession sqlSession = threadLocal.get();
if(sqlSession==null){
sqlSession = sqlSessionFactory.openSession(true);
System.out.println(sqlSession+",初始化SqlSession资源");
threadLocal.set(sqlSession);
}
return sqlSession;
}
public static void rollbackAndClose(SqlSession sqlSession) {
if (sqlSession != null) {
sqlSession.rollback();
sqlSession.close();
System.out.println(sqlSession+",回滚释放SqlSession资源");
threadLocal.remove();
}
}
public static void closeSession(SqlSession sqlSession){
sqlSession.commit();
sqlSession.close();
System.out.println(sqlSession+",释放SqlSession资源");
threadLocal.remove();
}
}
实体类–>Map优化 当实体类属性过多时,而其构造方法通常只有无参和全参两种,不太灵活,特别地修改某种属性时,不用构造一个实体类作为参数,而使用map传参。
5.总结
mybatis的CRUD三部曲 1.mapper接口定义方法 2.XML实现方法 3.测试方法 mybatis生命周期
6.使用注解配置
1.在映射接口中的方法前配置注解 2.在mybatis-config.xml中绑定接口
7.lombok简化pojo的开发
1.IDE安装lombok插件 2.pom.xml添加lombok依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
3.添加注解
|