简介
- MyBatis3前身是iBatis,本是Apache的一个开源的项目现在开源,代码放在gitjib平台商进行管理
网站
官网:https://mybatis.org/mybatis-3/
中文网:https://mybatis.net.cn/
持久层ORM框架
ORM(Object Relational Mapping)
- 编写程序的时候,以面向对象的方式处理数据
- 保存数据的时候却以关系型数据库的方式储存
ORM解决方案包含下面四个部分
- 在对持久化对象提供一种查询语言或者API
- 持久化对象上执行基本的增、删、改、查操作
- 对象关系映射工具
- 提供与事务对象交互、执行检查、延迟加载以及其他优化功能
特点
基于SQL语法,简单易学 |
能了解底层封装过程 |
SQL语句封装在配置文件中,便于统一管理与维护,降低程序的耦合 |
与JDBC的区别
搭建MyBatis开发环境
下载mybatis-3.2.2.jar包并导入工程
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.6version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.hamcrestgroupId>
<artifactId>hamcrest-coreartifactId>
<version>1.3version>
<scope>testscope>
dependency>
dependencies>
使用MyBatis的开发步骤
编写Mybatis核心配置文件(configuration.xml)
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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/ytzl/mybatis/mapper/StudentMapper.xml"/>
mappers>
configuration>
创建实体类-POJO
package com.ytzl.mybatis.pojo;
import java.util.Date;
public class Student {
private Integer id;
private String stuName;
private String address;
private Date birthday;
private Integer tid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", address='" + address + '\'' +
", birthday=" + birthday +
", tid=" + tid +
'}';
}
}
DAO层-SQL映射文件(mapper.xml)
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectStudent" resultType="com.ytzl.mybatis.pojo.Student">
select * from student where id = #{id}
select>
mapper>
创建测试类
package com.ytzl.mybatis.test;
import com.ytzl.mybatis.pojo.Student;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class JunitTest {
@Test
public void testSelectStudent() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
System.out.println(sqlSessionFactory);
SqlSession sqlSession = sqlSessionFactory.openSession();
Student stu = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectStudent", 1);
System.out.println(stu);
}
}
读取核心配置文件mybatis-config.xml
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
System.out.println(sqlSessionFactory);
创建SqlSessionFactory对象,读取配置文件
SqlSession sqlSession = sqlSessionFactory.openSession();
创建SqlSession对象
Student stu = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectStudent", 1);
调用mapper文件进行数据操作
System.out.println(stu);
MyBatis使用接口开发
视图
文件目录
mapper
StudentMapper
package mybatis.mapper;
import mybatis.pojo.Student;
public interface StudentMapper {
Student selectStudent(Integer id);
}
StudentMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.mapper.StudentMapper">
<select id="selectStudent" resultType="mybatis.pojo.Student">
select * from student where id = #{id}
select>
mapper>
pojo
Student
package mybatis.pojo;
import java.util.Date;
public class Student {
private Integer id;
private String stuName;
private String address;
private Date birthday;
private Integer tid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", address='" + address + '\'' +
", birthday=" + birthday +
", tid=" + tid +
'}';
}
}
Test
JunTest
package mybatis.test;
import mybatis.mapper.StudentMapper;
import mybatis.pojo.Student;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class JunitTest {
@Test
public void testSelectStudentMapper() {
String url = "mybatis-config.xml";
SqlSession session = null;
try {
InputStream inputStream = Resources.getResourceAsStream(url);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
System.out.println(studentMapper);
Student student = studentMapper.selectStudent(1);
System.out.println(student);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (session!=null){
session.close();
}
}
}
}
MyBatis核心对象
核心接口和类的结构
SqlSessionFactoryBuilder
用过即丢,其生命周期只存在于方法内 |
可重用起来创建多个SqlSessionFactory实例 |
负责构建SqlSessionFactory,并提供多个build方法的重载 |
SqlSessionFactory
SqlSessionFactory是每个MyBatis应用的核心 |
作用:创建SqlSession实例 |
SqlSession session = sqlSessionFactory.openSession(boolean autoCommt); //false true(默认)开启/关闭事务控制 |
作用域:Application |
生命周期与应用的生命周期相同 |
单例: |
存在于整个应用运行时,并且同时只存在一个对象实例 |
MybatisUtil
package mybatis.util;
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;
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
String url = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(url);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
public static void closeSession(SqlSession session){
session.close();
}
}
测试
@Test
public void testUtil() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
System.out.println(mapper);
Student student = mapper.selectStudent(1);
System.out.println(student);
MybatisUtil.closeSession(sqlSession);
}
SqlSession
包含了执行SQL所需的所有方法 |
对应一次数据库会话,会话结束必须关闭 |
线程级别,不能共享 |
SqlSession的获取方式
String resource = "mybatis-config.xml";
InputStream is = Resoutces.getResourceAsStream(resource)
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
SqlSession的两种使用方式
通过SqlSession实例直接运行映射的SQL语句
基于Mapper接口方式操作数据
小结
核心配置文件
目标
理解核心配置文件中的各项参数配置 |
掌握通过sQL映射文件进行增删改查 |
系统核心配置文件
configuration配置 |
|
properties |
可以配置在Java属性配置文件中 |
settings |
修改MyBatis在运行时的行为方式 |
typeAliases |
为Java类型命命名一个别名(简称) |
typeHandlers |
类型处理器 |
objectFactory |
对象工厂 |
plugins |
插件 |
environments |
环境 |
environment |
环境变量 |
|transactionManager |
事务管理器 |
|dataSource |
数据源 |
mappers |
映射器 |
properties
peoperties |
通过property标签添加属性 |
name |
属性名 |
value |
属性值 |
resource |
resource=“data.properties” |
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="data.properties">
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="${name}"/>
<property name="password" value="${pwd}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mybatis/mapper/StudentMapper.xml"/>
mappers>
configuration>
data.properties
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://localhost:3306/mybatis
name:root
pwd:123456
settings
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为 |
https://mybatis.net.cn/configuration.html#properties
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
typeAliases
typeAlias
typeAlias标签 |
单个类配置 |
alias属性 |
可以省略,默认是类名的首字母小写,不区分大小写 |
package
package标签 |
包路径下统一配置,也可以通过@Alias注解手动配置 |
name |
包的路径 |
@Alias注解 |
默认是类名的首字母小写,不区分大小写 |
<typeAliases>
<package name="mybatis.pojo"/>
typeHandler
typeHandler标签 |
类型处理器 |
handler |
处理器的完全路径名 |
jdbcType |
数据库类型 |
javaType |
类型 |
<typeHandlers
handler="mybatis.util.MyTypeHandler" jdbcType="INTEGER" javaType="String"/>
typeHandlers>
MyTypeHandler
package mybatis.util;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MyTypeHandler implements TypeHandler<String> {
@Override
public void setParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
int f = 1;
if (s.equals("女")){
f = 0;
}
preparedStatement.setInt(i,f);
}
@Override
public String getResult(ResultSet resultSet, String s) throws SQLException {
System.out.println("String ==>"+s);
return resultSet.getInt(s)==0?"女":"男";
}
@Override
public String getResult(ResultSet resultSet, int i) throws SQLException {
System.out.println("int ==>"+i);
return resultSet.getInt(i)==0?"女":"男";
}
@Override
public String getResult(CallableStatement callableStatement, int i) throws SQLException {
System.out.println("callableStatement ==>"+i);
return callableStatement.getInt(i)==0?"女":"男";
}
}
objectFactory&plugins
environments
transactionManager
mappers
<mapper resource="mybatis/mapper/StudentMapper.xml"/>
<mapper url="file:///F:/JavaWorkSpace/MyBatis/MyBatis_4/src/main/java/mybatis/mapper/StudentMapper.xml ">mapper>
<mapper class="mybatis.mapper.StudentMapper">mapper>
<package name="mybatis.mapper"/>
SQL映射的XML文件
MyBatis真正的强大在于映射语句!专注于SQL,功能强大,SQL映射的配置却是相当简单 |
select
StudentMapper
List<Student> selectAll();
mapper
<select id="selectAll" resultType="Student">
select * from student
select>
Test
@Test
public void testSelectAll(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
System.out.println(mapper);
List<Student> students = mapper.selectAll();
for (Student student:students){
System.out.println(student);
}
MybatisUtil.closeSession(sqlSession);
}
insert
StudentMapper
int addStudent(Student student);
MyTypeHandler
package mybatis.util;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MyTypeHandler implements TypeHandler<String> {
@Override
public void setParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
int f = 1;
if (s.equals("女")){
f = 0;
}
preparedStatement.setInt(i,f);
}
@Override
public String getResult(ResultSet resultSet, String s) throws SQLException {
System.out.println("String ==>"+s);
return resultSet.getInt(s)==0?"女":"男";
}
@Override
public String getResult(ResultSet resultSet, int i) throws SQLException {
System.out.println("int ==>"+i);
return resultSet.getInt(i)==0?"女":"男";
}
@Override
public String getResult(CallableStatement callableStatement, int i) throws SQLException {
System.out.println("callableStatement ==>"+i);
return callableStatement.getInt(i)==0?"女":"男";
}
}
mybatis-config.xml
<typeAliases>
<typeAlias type="mybatis.util.MyTypeHandler" alias="MyTypeHandler"/>
<package name="mybatis.pojo"/>
typeAliases>
mapper
<insert id="addStudent" parameterType="Student">
insert into student values (0,#{stuName},#{tid},#{address},#{birthday},#{sex,javaType=String,jdbcType=INTEGER,typeHandler=MyTypeHandler})
insert>
Test
@Test
public void testAddStudent() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int addStudent = mapper.addStudent(new Student("任俊楠", "413", new Date(), 45, "男"));
sqlSession.commit();
System.out.println(addStudent > 0 ? "增加成功" : "增加失败");
MybatisUtil.closeSession(sqlSession);
}
updata
StudentMapper
int updateStudent(@Param("id") int id,@Param("name") String name);
mapper
<update id="updateStudent">
update student set stu_name = #{name} where id = #{id}
update>
Test
@Test
public void testUpdateStudent() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int newName = mapper.updateStudent(1, "葛霄");
System.out.println("newName==>"+newName);
sqlSession.commit();
System.out.println(newName > 0 ? "修改成功" : "修改失败");
MybatisUtil.closeSession(sqlSession);
}
delete
StudentMapper
int deleteStudent(int id);
mapper
<delete id="deleteStudent" parameterType="int">
delete from student where id = #{id}
delete>
Test
@Test
public void testDeleteStudent() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int del = mapper.deleteStudent(1);
sqlSession.commit();
System.out.println(del > 0 ? "删除成功" : "删除失败");
MybatisUtil.closeSession(sqlSession);
}
MyBatis参数使用和量表联查
基础数据类型
单个参数
StudentMapper.xml
<select id="selectByName" parameterType="string" resultType="student">
select * from student where stu_name like concat('%',#{name},'%')
select>
StudentMapper
List<Student> selectByName(String name);
Test
@Test
public void testSelectByName() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student = mapper.selectByName("任");
System.out.println(student);
MybatisUtil.closeSession(sqlSession);
}
多个参数
StudentMapper.xml
<select id="selectByNameAndSex" resultType="student">
select * from student where stu_name like concat('%',#{name},'%') and sex = #{sex,javaType=String,jdbcType=INTEGER,typeHandler=MyTypeHandler}
select>
StudentMapper
Student selectByNameAndSex(@Param("name") String name,@Param("sex") String sex);
Test
@Test
public void testSelectByNameAndSex() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student = mapper.selectByName("任");
System.out.println(student);
Student student1 = mapper.selectByNameAndSex("任","男");
System.out.println(student1);
MybatisUtil.closeSession(sqlSession);
}
复杂数据类型
数组
StudentMapper
int deleteByIds(int[] ids);
StudentMapper.xml
<delete id="deleteByIds" parameterType="int">
delete from student where id in
<foreach collection="array" open="(" close=")" item="id" separator=",">
#{id}
foreach>
delete>
Test
@Test
public void testDelectByIds() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int[] ids = {1,2};
int i = mapper.deleteByIds(ids);
System.out.println(i);
sqlSession.commit();
MybatisUtil.closeSession(sqlSession);
}
List
StudentMapper
int deleteByList(List<Integer> ids);
StudentMapper.xml
<delete id="deleteByList" parameterType="int">
delete from student where id in
<foreach collection="list" open="(" close=")" item="id" separator=",">
#{id}
foreach>
delete>
Test
@Test
public void testDelectList() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Integer> list = new ArrayList<>();
list.add(12);
int i = mapper.deleteByList(list);
System.out.println(i);
sqlSession.commit();
MybatisUtil.closeSession(sqlSession);
}
Map ***
StudentMapper
List<Student> selectStuByCondition(Map<String,Object> map);
StudentMapper.xml
<select id="selectStuByCondition" parameterType="map" resultType="student">
select * from student s
where stu_name like concat('%',#{name},'%')
and TIMESTAMPDIFF(YEAR , s.birthday,now()) >=#{minAge}
and TIMESTAMPDIFF(YEAR , s.birthday,now()) <=#{maxAge}
and (address = #{address1} or address = #{address2})
select>
Test
@Test
public void testSelectMap() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Map<String,Object> map = new HashMap<>();
map.put("name","任");
map.put("minAge","16");
map.put("maxAge","20");
map.put("address1","413");
map.put("address2","416");
List<Student> students = mapper.selectStuByCondition(map);
System.out.println(students);
MybatisUtil.closeSession(sqlSession);
}
MyBatis中$和#的区别
两者都可以从Mybatis中取出参数 |
使用场景 |
一般情况下使用’#’ |
当数据库表名或字段名需要动态入参的时候需要用"$" |
例如: |
order by${birthday}根据出生日期排序 |
|
解析方式 |
防止SQL注入 |
使用场景 |
“#” |
默认会加上引号,如: |
是 |
一般情况使用 |
|
order by #{id},如果id值为1则解析为order by"1" |
|
|
“$” | |
默认不会加上引号 如: |
否 |
${}方式一般用于传入数据库对象, |
|
order by #{id},如果id值为1则解析为order by id |
|
例如传入表名、列名 |
StudentMapper
List<Student> selectStudentOrder(String order);
StudentMapper.xml
<select id="selectStudentOrder" parameterType="string" resultType="Student">
select * from student order by ${_parameter}
select>
Test
@Test
public void testOrder() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> birthday = mapper.selectStudentOrder("birthday");
System.out.println(birthday);
MybatisUtil.closeSession(sqlSession);
}
结果集映射
使用resultMap如何实现自由灵活的控制映射结果 |
resultMap自动映射匹配前提:字段名与属性名一致 |
resultMap的自动映射级别–>autoMappingBehaior |
PARTIAL(默认):自动匹配所有 |
属性 |
说明 |
property |
实体类的字段 |
column |
数据库里的字段 |
|
|
StudentResultMapper
List<Student> selectStudent();
StudentResultMapper.xml
<resultMap id="StudentResult" type="Student">
<id column="id" property="id">id>
<result column="stu_name" property="stuName">result>
<result column="address" property="address">result>
resultMap>
<select id="selectStudent" resultMap="StudentResult">
select * from student
select>
Test
@Test
public void testResult() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentResultMapper resultMapper = sqlSession.getMapper(StudentResultMapper.class);
List<Student> students = resultMapper.selectStudent();
for (Student stu:students){
System.out.println(stu);
}
MybatisUtil.closeSession(sqlSession);
}
关联映射一对一
StudentResultMapper
List<Student> selectStudent();
List<Student> selectStudentAndTeacher();
StudentResultMapper.xml
<resultMap id="StudentAndTeacherResult" type="Student">
<id column="id" property="id">id>
<result column="stu_name" property="stuName">result>
<result column="address" property="address">result>
<association property="teacher" javaType="teacher">
<id column="id" property="id">id>
<result column="tName" property="name">result>
<result column="tel" property="tel">result>
<result column="age" property="age">result>
<result column="sex" property="sex">result>
<result column="address" property="address">result>
association>
resultMap>
<select id="selectStudentAndTeacher" resultMap="StudentAndTeacherResult">
select * from student s, teacher t
where s.tid = t.id
select>
Student
package mybatis.pojo;
import org.apache.ibatis.type.Alias;
import java.util.Date;
@Alias("Student")
public class Student {
private Integer id;
private String stuName;
private String address;
private Date birthday;
private Integer tid;
private String sex;
public Teacher teacher;
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public Student(Integer id, String stuName, String address, Date birthday, Integer tid, String sex) {
this.id = id;
this.stuName = stuName;
this.address = address;
this.birthday = birthday;
this.tid = tid;
this.sex = sex;
}
public Student(String stuName, String address, Date birthday, Integer tid, String sex) {
this.stuName = stuName;
this.address = address;
this.birthday = birthday;
this.tid = tid;
this.sex = sex;
}
public Student(String stuName, String address, Date birthday, Integer tid) {
this.stuName = stuName;
this.address = address;
this.birthday = birthday;
this.tid = tid;
}
public Student() {
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", address='" + address + '\'' +
", birthday=" + birthday +
", tid=" + tid +
", sex='" + sex + '\'' +
'}';
}
}
Teacher
package mybatis.pojo;
public class Teacher {
private Integer id;
private String name;
private String tel;
private Integer age;
private String sex;
private Integer address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAddress() {
return address;
}
public void setAddress(Integer address) {
this.address = address;
}
public Teacher(Integer id, String name, String tel, Integer age, String sex, Integer address) {
this.id = id;
this.name = name;
this.tel = tel;
this.age = age;
this.sex = sex;
this.address = address;
}
}
Test
@Test
public void testStuAdnTea() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentResultMapper resultMapper = sqlSession.getMapper(StudentResultMapper.class);
List<Student> students = resultMapper.selectStudentAndTeacher();
for (Student stu:students){
System.out.println(stu);
}
MybatisUtil.closeSession(sqlSession);
}
关联映射分步查询
StudentResultMapper
package mybatis.mapper;
import mybatis.pojo.Student;
import java.util.List;
public interface StudentResultMapper {
List<Student> selectStudent();
List<Student> selectStudentAndTeacher();
List<Student> selectStudentAndTeacherTwo();
}
TeacherMapper
package mybatis.mapper;
import mybatis.pojo.Teacher;
public interface TeacherMapper {
Teacher selectByTid(Integer tid);
}
StudentResultMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.mapper.StudentResultMapper">
<resultMap id="StudentResult" type="Student">
<id column="id" property="id">id>
<result column="stu_name" property="stuName">result>
<result column="address" property="address">result>
resultMap>
<select id="selectStudent" resultMap="StudentResult">
select * from student
select>
<resultMap id="StudentAndTeacherResult" type="Student">
<id column="id" property="id">id>
<result column="stu_name" property="stuName">result>
<result column="address" property="address">result>
<association property="teacher" select="mybatis.mapper.TeacherMapper.selectByTid" column="tid">association>
resultMap>
<resultMap id="TeacherResult" type="Teacher">
<id column="id" property="id">id>
<result column="tName" property="name">result>
<result column="tel" property="tel">result>
<result column="age" property="age">result>
<result column="sex" property="sex">result>
<result column="address" property="address">result>
resultMap>
<select id="selectStudentAndTeacherTwo" resultMap="StudentAndTeacherResult">
/* select * from student s, teacher t
where s.tid = t.id*/
select * from student
select>
mapper>
TeacherMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.mapper.TeacherMapper">
<select id="selectByTid" parameterType="int" resultType="Teacher">
select * from teacher where id = #{tid}
select>
mapper>
Test
@Test
public void testSelectTeaResult() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.selectByTid(1);
System.out.println(teacher);
MybatisUtil.closeSession(sqlSession);
}
@Test
public void testStuAdnTeaTwo() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentResultMapper resultMapper = sqlSession.getMapper(StudentResultMapper.class);
List<Student> students = resultMapper.selectStudentAndTeacherTwo();
for (Student stu:students){
System.out.println(stu);
}
MybatisUtil.closeSession(sqlSession);
}
分步查询多列传值和延迟加载
StudentResultMapper
package mybatis.mapper;
import mybatis.pojo.Student;
import java.util.List;
public interface StudentResultMapper {
List<Student> selectStudent();
List<Student> selectStudentAndTeacher();
List<Student> selectStudentAndTeacherTwo();
}
StudentResultMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.mapper.StudentResultMapper">
<resultMap id="StudentResult" type="Student">
<id column="id" property="id">id>
<result column="stu_name" property="stuName">result>
<result column="address" property="address">result>
resultMap>
<select id="selectStudent" resultMap="StudentResult">
select * from student
select>
<resultMap id="StudentAndTeacherResult" type="Student">
<id column="id" property="id">id>
<result column="stu_name" property="stuName">result>
<result column="address" property="address">result>
<association property="teacher" select="mybatis.mapper.TeacherMapper.selectByTid" column="{tid=tid}">association>
resultMap>
<resultMap id="TeacherResult" type="Teacher">
<id column="id" property="id">id>
<result column="tName" property="name">result>
<result column="tel" property="tel">result>
<result column="age" property="age">result>
<result column="sex" property="sex">result>
<result column="address" property="address">result>
resultMap>
<select id="selectStudentAndTeacherTwo" resultMap="StudentAndTeacherResult">
/* select * from student s, teacher t
where s.tid = t.id*/
select * from student
select>
mapper>
TeacherMapper
package mybatis.mapper;
import mybatis.pojo.Teacher;
public interface TeacherMapper {
Teacher selectByTid(Integer tid);
}
TeacherMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.mapper.TeacherMapper">
<select id="selectByTid" resultType="Teacher">
select * from teacher where id = #{tid}
select>
mapper>
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="data.properties">
properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="autoMappingBehavior" value="FULL"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
settings>
<typeAliases>
<typeAlias type="mybatis.util.MyTypeHandler" alias="MyTypeHandler"/>
<package name="mybatis.pojo"/>
typeAliases>
<typeHandlers>
<typeHandler handler="mybatis.util.MyTypeHandler" jdbcType="INTEGER" javaType="String"/>
typeHandlers>
<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="${name}"/>
<property name="password" value="${pwd}"/>
dataSource>
environment>
environments>
<mappers>
<package name="mybatis.mapper"/>
mappers>
configuration>
关联查询一对多
StudentResultMapper
List<Student> selectByTid(Integer tid);
StudentResultMapper.xml
<select id="selectByTid" parameterType="int" resultType="Student">
select * from student where tid = #{tid}
select>
TeacherMapper
Teacher selectInfoBytid(Integer tid);
TeacherMapper.xml
<resultMap id="TeacherMap" type="Teacher">
<collection property="stuList" select="mybatis.mapper.StudentResultMapper.selectByTid" column="id">collection>
resultMap>
<select id="selectInfoBytid" resultMap="TeacherMap">
select * from teacher where id=#{id}
select>
Test
@Test
public void testStuAdnTeaTwo() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentResultMapper mapper = sqlSession.getMapper(StudentResultMapper.class);
List<Student> students = mapper.selectByTid(1);
for (Student stu:students){
System.out.println(stu);
}
MybatisUtil.closeSession(sqlSession);
}
@Test
public void testSelectInfoTeaByTid() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.selectByTid(1);
System.out.println(teacher.getName());
MybatisUtil.closeSession(sqlSession);
}
动态SQL
用户实现动态SQL的元素主要有
元素 |
|
if |
|
where |
|
trim |
|
set |
|
choos(when\otherwise) |
|
foreach |
|
if&where
SqlMapper
List<Student> selectByNameAndSex(@Param("stuName") String stuName,@Param("sex") String sex);
SqlMapper.xml
<select id="selectByNameAndSex" resultType="student">
select * from student
<where>
<if test="stuName!=null and stuName!=''">
and stu_name like concat('%',#{stuName},'%')
if>
<if test="sex!=null and sex!=''">
and sex =#{sex,javaType=String,jdbcType=INTEGER,typeHandler=MyTypeHandler}
if>
where>
select>
Test
@Test
public void testStuAdnTeaTwo() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
List<Student> students = mapper.selectByNameAndSex("任", "0");
System.out.println(students);
MybatisUtil.closeSession(sqlSession);
}
Set
SqlMapper
int updateStudent(Student stu);
SqlMapper.xml
<update id="updateStudent" parameterType="student">
update student
<set>
<if test="stuName!=null and stuName!=''">stu_name=#{stuName},if>
<if test="address!=null and address!=''">address=#{address},if>
<if test="birthday!=null and birthday!=''">birthday=#{birthday},if>
<if test="sex!=null and sex!=''">sex=#{sex,javaType=String,jdbcType=INTEGER,typeHandler=MyTypeHandler},if>
<if test="tid!=null and tid!=''">tid=#{tid},if>
set>
<where>
<if test="id!=null and id!=''">
id=#{id}
if>
where>
update>
Test
@Test
public void testSqlUpdate() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
Student student = new Student();
student.setId(14);
student.setStuName("牛雷雨");
int i = mapper.updateStudent(student);
System.out.println(i);
sqlSession.commit();
MybatisUtil.closeSession(sqlSession);
}
trim
属性 |
|
prefix |
|
suffix |
|
prefixOverrides |
|
suffixOverrides |
|
修改
SqlMapper
int updateStudent(Student stu);
SqlMapper.xml
<update id="updateStudent" parameterType="student">
update student
<trim prefix="set" suffix="where id=#{id}" suffixOverrides=",">
<if test="stuName!=null and stuName!=''">stu_name=#{stuName},if>
<if test="address!=null and address!=''">address=#{address},if>
<if test="birthday!=null and birthday!=''">birthday=#{birthday},if>
<if test="sex!=null and sex!=''">sex=#{sex,javaType=String,jdbcType=INTEGER,typeHandler=MyTypeHandler},if>
<if test="tid!=null and tid!=''">tid=#{tid},if>
trim>
update>
Test
@Test
public void testSqlUpdate() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
Student student = new Student();
student.setId(15);
student.setSex("男");
student.setStuName("牛雷雨");
int i = mapper.updateStudent(student);
System.out.println(i);
sqlSession.commit();
MybatisUtil.closeSession(sqlSession);
}
查询
SqlMapper.xml
<select id="selectByNameAndSex" resultType="student">
select * from student
<trim suffix="where" prefixOverrides="and">
<if test="stuName!=null and stuName!=''">
stu_name like concat('%',#{stuName},'%')
if>
<if test="sex!=null and sex!=''">
and sex =#{sex,javaType=String,jdbcType=INTEGER,typeHandler=MyTypeHandler}
if>
trim>
select>
foreach&choose
foreach
SqlMapper
List<Student> selectChoose(Map<String,Object> map);
SqlMapper.xml
<select id="selectChoose" parameterType="map" resultType="student">
select * from student
<where>
<choose>
<when test="stuName!=null and stuName!=''">and stu_name like concat('%',#{stuName},'%')when>
<when test="sex!=null and sex!=''">and sex =#{sex,javaType=String,jdbcType=INTEGER,typeHandler=MyTypeHandler}when>
<when test="minBirthday!=null and minBirthday!=''">and birthday >=#{minBirthday}when>
<when test="maxBirthday!=null and maxBirthday!=''">and birthday <=#{maxBirthday}when>
<otherwise>and address like concat('%',#{address},'%')otherwise>
choose>
where>
select>
Test
@Test
public void testSqlSelectChoose() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("stuName","任");
map.put("minBirthday","1999-04-27");
List<Student> students = mapper.selectChoose(map);
System.out.println(students);
MybatisUtil.closeSession(sqlSession);
}
分页查询
SqlMapper
List<Student> selectStudent(@Param("start") Integer start,@Param("size")Integer size);
int getCount();
SqlMapper.xml
<select id="selectStudent" resultType="Student">
select * from student limit #{start} , #{size}
select>
<select id="getCount" resultType="int">
select count(id) from student
select>
Page
package mybatis.pojo;
import java.util.List;
public class Page {
private Integer pageIndex;
private Integer pageSize;
private Integer totalCount;
private Integer totalPage;
private List<Student> stuList;
public Page(Integer pageIndex, Integer pageSize) {
this.pageIndex = pageIndex;
this.pageSize = pageSize;
}
public Page() {
}
public Integer getPageIndex() {
return pageIndex;
}
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<Student> getStuList() {
return stuList;
}
public void setStuList(List<Student> stuList) {
this.stuList = stuList;
}
}
Test
@Test
public void testSqlPage() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
int pageIndex = 1;
int pageSize = 3;
Page page = new Page(pageIndex,pageSize);
int count = mapper.getCount();
page.setTotalPage(count);
int totalPage = count%pageSize==0? count/pageSize:count/pageSize+1;
page.setTotalPage(totalPage);
List<Student> students = mapper.selectStudent((pageIndex - 1) * pageSize, pageSize);
page.setStuList(students);
System.out.println(students);
MybatisUtil.closeSession(sqlSession);
}
Mybatis缓存
方法
sqlSession.clearCache() |
清楚缓存 |
|
|
|
|
|
|
一级缓存
- 默认开启
- 同一次数据库会话有效
- 手动调用清楚缓存的方法sqlSession.clearCache();缓存失效
- 调用增删改时缓存也会失效
二级缓存
使用
配置核心配置文件
<setting name="cacheEnabled" value="true">setting>
配置mapper.xml
<cache eviction="LRU" flushInterval="60000" size="10240" readOnly="true">cache>
特点
- 作用于整个selsessionfactory
- 可以单独进行配置是否使用缓存
<select id="selectByNameAndSexResult" resultType="Student" flushCache="true">
第三方缓存EhCache
自动生成工具generator
导入必要pom依赖:
<dependencies>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.6version>
dependency>
dependencies>
核心配置文件
DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<plugin type="org.mybatis.generator.plugins.MapperConfigPlugin">
<property name="fileName" value="GeneratedMapperConfig.xml" />
<property name="targetPackage" value="mapper" />
<property name="targetProject" value="C:\code\resources\" />
plugin>
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="123456">
jdbcConnection>
<javaModelGenerator targetPackage="com.ytzl.pojo" targetProject="src/main/java"/>
<sqlMapGenerator targetPackage="com.ytzl.mapper" targetProject="src/main/java"/>
<javaClientGenerator targetPackage="com.ytzl.dao" targetProject="src/main/java" type="XMLMAPPER" />
<table tableName="%" >
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
table>
context>
generatorConfiguration>
启动 GeneratorDisplay
package com.ytzl.util;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GeneratorDisplay {
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("F:\\JavaWorkSpace\\MyBatis\\Genertor\\generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
public static void main(String[] args) throws Exception {
try {
GeneratorDisplay generatorSqlmap = new GeneratorDisplay();
generatorSqlmap.generator();
System.out.println("ok");
} catch (Exception e) {
e.printStackTrace();
}
}
}
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="data.properties">
properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="autoMappingBehavior" value="FULL"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
settings>
<typeAliases>
<typeAlias type="com.ytzl.util.MyTypeHandler" alias="MyTypeHandler"/>
<package name="com.ytzl.pojo"/>
typeAliases>
<typeHandlers>
<typeHandler handler="com.ytzl.util.MyTypeHandler" jdbcType="INTEGER" javaType="String"/>
typeHandlers>
<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="${name}"/>
<property name="password" value="${pwd}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/ytzl/mapper/TeacherMapper.xml">mapper>
<package name="com.ytzl.dao.TeacherMapper">package>
mappers>
configuration>
分页插件pagehelper
参考地址https://pagehelper.github.io/
依赖导入
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.1.10version>
dependency>
mybatis-config.xml
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
<property name="pageSizeZero" value="true"/>
<property name="reasonable" value="true"/>
plugin>
plugins>
测试
@Test
public void test分页() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
PageHelper.startPage(1, 2);
List<Student> students = mapper.selectAll();
System.out.println("students==>"+students);
MybatisUtil.closeSession(sqlSession);
}