概述
官方文档:https://mybatis.org/mybatis-3/zh/index.html
1.1什么是Mybatis
- 一款优秀的持久层框架(持久化:将程序的数据从瞬时状态转化为持久状态的过程,通常是写入数据库,磁盘等)
- 支持定制化SQL,储存过程以及高级映射
- 规避了JDBC使用的复杂性,简单易上手
- 原名iBatis(有的jar包还是这个名字),现源码在GitHub上
1.2Mybatis用来干什么?
- 帮我们实现对数据库的操作,简单方便,替我们完成传统的,复杂的jdbc代码方式实现的工作
- SQL和代码分离,我们只需要在xml中编写SQL就可以实现对数据库的操作
- 提供对象关系映射标签,支持对象与数据库里的orm字段关系映射(过去我们封装的jdbc工具类的工作)
使用
搭建环境
导入Mybatis,或者maven方式导入依赖(mysql,mybatis,junit三个包)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
配置相关属性(两种方式)
-
application.properties中进行配置(推荐)
#数据连接 spring.datasource.url=jdbc:mysql://115.159.160.***:3306/mydb?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=myuser spring.datasource.password=123456 spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver #Mybatis扫描 mybatis.type-aliases-package=com.example.demo.entity mybatis.mapper-locations=classpath*:mapper/*.xml mybatis.configuration.mapUnderscoreToCamelCase=true
-
或者创建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="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!--根据情况可能不需要 --> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
SQL实现
创建dao的接口
@Mapper
public interface StudentDao {
/**
* 获取学生信息
* @return
*/
List<Student> getStudents();
}
该接口的实现类由StudentDaoMapper.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="edu.njxjc.study.dao.api.dao.StudentDao">
<select id="getStudents" resultType="edu.njxjc.study.dao.api.entity.Student">
<![CDATA[
select * from student;
]]>
</select>
</mapper>
建立映射关系(两种方式)
-
添加Mapper注释(推荐方法,简单)
只需要在相应的dao接口添加注释@Mapper(如上代码),就可以直接使用了,sql语句可以正常执行。
-
自定义工具类获取Sqlsession
-
编写MybatisUtil,用于获取Sqlsession
String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
建立映射关系,实现接口
SqlSession sqlSession = MybatisUtil.getSqlSession(); //获取SqlSession类 StudentDao studentDao = sqlSession.getMapper(StudentDao.class); //建立映射关系 List<Student> students = studentDao.getStudents(); //执行sql sqlSession.close() //关闭sqlSession
注意这种方式StudentDaoMapper.xml中的namespace名字要与配置文件中的resource保持一致,注意接口名
<mappers> <mapper resource="edu.njxjc.study.dao.api.dao.StudentMapper.xml"/> </mappers> <mapper namespace="edu.njxjc.study.dao.api.dao.StudentMapper"></mapper>
-