一.文件目录
二 环境搭建
2.1框架依赖(MySQL依赖根据自己的版本)
junit junit 4.12 test mysql mysql-connector-java 8.0.21 org.mybatis mybatis 3.5.7 log4j log4j 1.2.17 ### 2.2.配置文件 #### 2.2.1mybatis-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?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,
reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)"-->
<!-- 引入 properties -->
<properties resource="jdbc.properties"/>
<!-- 设置类型别名(不区分大小写) -->
<typeAliases>
<!-- 默认是类名 alias别名内容(可省略)-->
<!-- <typeAlias type="com.remained.pojo.Student" alias="User"/>-->
<package name="com.remained.pojo"/>
</typeAliases>
<!-- environments 配置连接数据库的多个环境
default 默认使用的一个环境
id 单个环境的唯一标识-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- transactionManager 设置事务管理方式
属性type="JDBC/MANAGED"
JDBC 表示当前环境执行sql时用的是原生的JDBC事务管理(即需要手动处理)
MANAGED:被管理(例如spring)-->
<!-- 上面的并没有提交事务,所以我们要手动提交-->
<!-- type="POOLED" 数据库连接池的保存-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pwd}"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射文件-->
<mappers>
<!-- 引入单个映射文件-->
<!-- <mapper resource="mappers/StudentMapper.xml"/>-->
<!-- 如果映射多个文件也可以使用package标签-->
<!-- 1.mapper接口所在的包要和映射接口所在的包一致
2.mapper接口要和映射文件的名字一致 -->
<package name="com.remained.mapper"/>
</mappers>
</configuration>
2.2.2 jdbc.properties (mysql8的Driver和5不同)
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/mybatis_test?serverTimezone=UTC
jdbc.user=root
jdbc.pwd=123456
2.2.3
映射文件Mapper的配置
<?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">
DOCTYPE 后面的必是配置文件中的根标签-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.remained.mapper.StudentMapper">
</mapper>
2.2.4 log4j.xml (log4j日志配置)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}
%m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<!-- name 是范围-->
<!-- level是级别FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)-->
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
2.2.5 实体类 Student
package com.remained.pojo;
/**
* Project:MyBatis
* Date:2022/4/10
* Time:16:37
* Description:TODO
*
* @author lmk
* @version 1.0
*/
public class Student {
private int id;
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
三 测试(通过添加数据进行测试)
public void te() throws IOException {
//加载核心配置文件(可以是很多方式获取比如文件,配置文件等等,这里是字节输入流)
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder 工厂对象的构造对象
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
//通过SqlSessionFactoryBuilder建立SqlSessionFactory 建立工厂对象
SqlSessionFactory build = sfb.build(is);
//获取sql会话(和web中的HTTPSession差不多) sqlSession 访问sql语句,执行SQL语句获得其结果
//参数ture 就是可以自动提交事务
SqlSession sqlSession = build.openSession(true);
//获取mapper接口对象 Mybatis底层自动(动态地)帮我们创建了其实现类 它就帮我们获取一个类的实例化对象
StudentMapper student = sqlSession.getMapper(StudentMapper.class);
//我们调用 StudentMapper接口中的方法 然后他就会找到映射文件即Student.xml 根据调用的方法然后找到sql语句
int res = student.addStudent();
//提交事务 用sqlSession
sqlSession.commit();
System.out.println(res);
}
3.1一些简单的增删改查
//因为 mybatis 提供了面向接口的编程
// 对象关系映射 O(Java中的类)R(关系型数据库)M(映射指的是两者之间的对应关系)
public interface StudentMapper {
// 添加数据 insert等的返回值是改变的行数 所以返回值类型是 int
//通过映射操作数据库,然后再把操作结果返回
/*
* 实现mybatis的两个一致
* 1.namespace 全类名 要和映射的接口一致
* 2.配置文件中的 id要和映射文件中的方法名一致*/
//一个Mapper接口 对应一个映射文件,一个映射文件对应一张表,一张表对应一个实体类
//添加信息
int addStudent();
//修改信息 不要返回值也可以
void updateStudent();
//删除信息
void deleteStudent();
//查询单个信息 用实体类即可
Student getStudentById();
//查询所有信息 用list
List<Student> getAllStudent();
//根据用户id获取学生信息
Student getNameById(int stuId);
//判断是否有这个学生
boolean isStudent(@Param("id") int id,@Param("name") String name);
//
void registerStudent(Student student);
}
<?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">
DOCTYPE 后面的必是配置文件中的根标签-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.remained.mapper.StudentMapper">
<!-- sql语句后面没;-->
<!-- int addStudent();-->
<insert id="addStudent">
insert into m_student values (10,"sky")
</insert>
<!-- void updateStudent();-->
<update id="updateStudent">
update m_student set name='remained' where id=1
</update>
<!-- void deleteStudent();-->
<delete id="deleteStudent" >
delete from m_student where name='sky'
</delete>
<!-- resultType 结果类型 默认映射关系 属性名和字段名一致 resultMap结果映射 自定义映射关系 是sql语句中的返回值 然后再把这个返回值返回给这个方法-->
<!-- 查询中的数据所对应实体类的类型 -->
<!-- 查询功能 必须设置resultType 或resultMap-->
<!-- Student getStudentById();-->
<select id="getStudentById" resultType="com.remained.pojo.Student" >
select * from m_student where id=1
</select>
<!-- List<Student> getAllStudent();-->
<select id="getAllStudent" resultType="com.remained.pojo.Student" >
select * from m_student
</select>
<!-- Student getNameById(int stuId);-->
<!-- select * from m_student where id='${stuId}' 字符串拼接要有单引号 {}里面的可以是任意变量,不影响-->
<select id="getNameById" resultType="Student">
select * from m_student where id=#{stuId}
</select>
<!-- boolean isStudent(int id,String name);-->
<select id="isStudent" resultType="boolean">
select * from m_student where id=#{arg0}
</select>
<!-- void registerStudent(Student student);-->
<insert id="registerStudent">
insert into m_student values(#{id},#{name})
</insert>
</mapper>
import com.remained.mapper.StudentMapper;
import com.remained.pojo.Student;
import com.remained.utils.SqlSessionUtil;
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;
import java.util.List;
import java.util.Properties;
/**
* Project:MyBatis
* Date:2022/4/10
* Time:18:01
* Description:TODO
*
* @author lmk
* @version 1.0
*/
public class MybatisTest {
/*工厂模式, 将我们创建对象的模式进行封装,直接提供我们所需要的对象*/
/*mybatis获取参数的两种方式
* 1.1${} 相当于字符串拼接 会存在sql注入问题
* 1.2#{} 相当于占位符 预编译
* 2. 获取多个参数时(虽然传入多个,但是可以只用一个)
* mybatis 自动把这些参数放在Map集合里面[arg0,arg1]为键[param1,param2]为键 也可以混着用 因为都在Map集合里面
* 可以自己把数据存入到自己建的map中,然后以自己命名的建当参数名 即#{studentName}
* 3.参数是一个实体类
* 属性主要看get和set方法
* 接收参数时应该用其实体类的属性名 即#{id}#{name}
* 4.使用@Param注解命名参数 ,这样就可以使用我们所命名的参数 而不用使用arg param
* isStudent(@Param("id") int id,@Param("name") String name);
* 此时就是 把arg 换成自己命名的 但是 param仍然可以使用
* */
@Test
public void te() throws IOException {
//加载核心配置文件(可以是很多方式获取比如文件,配置文件等等,这里是字节输入流)
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder 工厂对象的构造对象
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
//通过SqlSessionFactoryBuilder建立SqlSessionFactory 建立工厂对象
SqlSessionFactory build = sfb.build(is);
//获取sql会话(和web中的HTTPSession差不多) sqlSession 访问sql语句,执行SQL语句获得其结果
//参数ture 就是可以自动提交事务
SqlSession sqlSession = build.openSession(true);
//获取mapper接口对象 Mybatis底层自动(动态地)帮我们创建了其实现类 它就帮我们获取一个类的实例化对象
StudentMapper student = sqlSession.getMapper(StudentMapper.class);
//我们调用 StudentMapper接口中的方法 然后他就会找到映射文件即Student.xml 根据调用的方法然后找到sql语句
int res = student.addStudent();
//提交事务 用sqlSession
sqlSession.commit();
System.out.println(res);
}
@Test
public void te1() throws IOException {
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//sql工厂建造
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
//sql工厂
SqlSessionFactory factory = sfb.build(is);
//创建SQLSession
SqlSession sqlSession = factory.openSession(true);
//获取接口的实例化对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.updateStudent();
}
@Test
public void te2() throws IOException {
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//sql工厂建造
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
//sql工厂
SqlSessionFactory factory = sfb.build(is);
//创建SQLSession
SqlSession sqlSession = factory.openSession(true);
//获取接口的实例化对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//查询单个信息
// Student stu = mapper.getStudentById();
// System.out.println(stu);
List<Student> list = mapper.getAllStudent();
list.forEach(System.out::println);
}
@Test
public void te3(){
//使用自己写的工具类
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// Student stu = mapper.getNameById(1);
// System.out.println(stu);
// boolean isTure = mapper.isStudent(1,"remained");
// System.out.println(isTure);
mapper.registerStudent(new Student(11,"lx"));
}
}
3.2自己定义的工具类
package com.remained.utils;
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.InputStream;
/**
* Project:MyBatis
* Date:2022/4/11
* Time:18:38
* Description:TODO
*
* @author lmk
* @version 1.0
*/
public class SqlSessionUtil {
// 既然是工具类 抛异常用try catch 然后方法是静态
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sql = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sql.build(is);
sqlSession = sqlSessionFactory.openSession(true);
} catch (Exception e) {
e.printStackTrace();
}
return sqlSession;
}
}
3.3 一些常用的查询
package com.remained.mapper;
import com.remained.pojo.Student;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* Project:MyBatis
* Date:2022/4/11
* Time:22:19
* Description:TODO
*
* @author lmk
* @version 1.0
*/
public interface SelectMapper {
// 根据名字 查人的所有信息
Student getStudentByName(@Param("name") String name);
// 获取记录行数
int getCount();
// 根据名字 查人的所有信息 并以Map返回 Map 中的键一般设置为String 值设置成Object
Map<String,Object> getAllToMap(int id);
// 用注解获取多条数据 此时id为键 map中的信息为值
@MapKey("id")
Map<String,Object> getAllStudentToMap();
Student getStudentByLike(@Param("name")String name);
// 批量删除
int deleteManyStudent(String ids);
// 通过表名进行查询数据
List<Student> getStudentToTable(@Param("tableName") String tableName);
// 添加功能获取主键的自增功能
void insertStudent(Student student);
}
<?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">
DOCTYPE 后面的必是配置文件中的根标签-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.remained.mapper.SelectMapper">
<!-- Student getStudentByName(@Param("name") String name);-->
<select id="getStudentByName" resultType="Student">
select * from m_student where name=#{name}
</select>
<!-- count()字段null不算 和count(1/*) 查出来时不一样的 null算-->
<!-- resultType="int" 类型别名(不区分大小写), mybatis底层帮我们做了 -->
<!-- int getCount();-->
<select id="getCount" resultType="int">
select count(1) from m_student
</select>
<!-- Map<Object,Object> getAll(int id);-->
<select id="getAllToMap" resultType="map">
select * from m_student where id=#{id}
</select>
<select id="getAllStudentToMap" resultType="map">
select * from m_student
</select>
<!-- 模式查询 占位符会被当成字符串 因为有引号 导致我们为占位符赋值时找不到通配符-->
<!-- 可以用字符串拼接 select * from m_student where name like concat('%',#{name},'%')-->
<!-- 最常用的 select * from m_student where name like “%”#{name}”%“-->
<select id="getStudentByLike" resultType="Student">
select * from m_student where name like "%"#{name}"%"
</select>
<!-- int deleteManyStudent(String ids); #{ids}不行-->
<delete id="deleteManyStudent" >
delete from m_student where id in (${ids})
</delete>
<!-- List<Student> getStudentToTable(@Param("tableName") String tableName);-->
<select id="getStudentToTable" resultType="Student">
select * from ${tableName}
</select>
<!-- void insertStudent(Student student);-->
<insert id="insertStudent" useGeneratedKeys="true" keyProperty="id">
insert into m_student values (#{id},#{name})
</insert>
</mapper>
import com.remained.mapper.SelectMapper;
import com.remained.pojo.Student;
import com.remained.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
/**
* Project:MyBatis
* Date:2022/4/11
* Time:22:20
* Description:TODO
*
* @author lmk
* @version 1.0
*/
public class SelectTest {
/*
1.当查询的结果为多条数据必须要用List或者Map接收否则报错
2.map 只可以获取一个记录行 可以用list嵌套 用注解 @MapKey("id")
Map<String,Object> getAllStudentToMap();
3.查询多条数据 可以新建一个动态表进行查询 即参数是表名 但是表名是不能加引号的,所以不能使用#{}
* */
@Test
// 获取记录行数
public void t0(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getCount());
}
@Test
// 根据名字 查人的所有信息
public void t1(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getStudentByName("sky"));
}
@Test
// 根据名字 查人的所有信息 并以Map返回
// map 中的键对应实体类中的属性 值为value(map 内是无序的)
public void t2(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllToMap(1));
}
@Test
// 用注解获取多条数据 此时id为键 map中的信息为值
public void t3(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllStudentToMap());
// {1={name=remained, id=1}, 2={name=李四, id=2}, 10={name=sky, id=10}, 11={name=lx, id=11}}
}
@Test
// 模糊查询
public void t4(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getStudentByLike("k"));
}
@Test
// 批量删除
public void t5(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.deleteManyStudent("2,3"));
}
@Test
// 通过表名进行查询数据
public void t6(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
List<Student> m = mapper.getStudentToTable("m_student");
m.forEach(System.out::println);
}
@Test
// 添加功能获取主键的自增功能 实现之前先在MySQL设置主键递增
public void t7(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
Student student = new Student("success");
mapper.insertStudent(student);
System.out.println(student);
}
}
四 一些关于mybatis 的知识
4.1mybatis的特点
1) MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架
2) MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
3) MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java
Objects,普通的Java对象)映射成数据库中的记录
4) MyBatis 是一个 半自动的ORM(Object Relation Mapping)框架
4.2映射文件
1、映射文件的命名规则:
表所对应的实体类的类名+Mapper.xml
例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml
因此一个映射文件对应一个实体类,对应一张表的操作
MyBatis映射文件用于编写SQL,访问以及操作表中的数据
MyBatis映射文件存放的位置是src/main/resources/mappers目录下
2、MyBatis中可以面向接口操作数据,要保证两个一致:
a>mapper接口的全类名和映射文件的命名空间(namespace)保持一致
b>mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
4.3sqlSession
SqlSession:代表Java程序和数据库之间的会话。(HttpSession是Java程序和浏览器之间的
会话)
SqlSessionFactory:是“生产”SqlSession的“工厂”。
工厂模式:如果创建某一个对象,使用的过程基本固定,那么我们就可以把创建这个对象的
相关代码封装到一个“工厂类”中,以后都使用这个工厂类来“生产”我们需要的对象
4. 4 自动映射和自定义映射
1、查询的标签select必须设置属性resultType或resultMap,用于设置实体类和数据库表的映射
关系
resultType:自动映射,用于属性名和表中字段名一致的情况
resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况
2、当查询的数据为多条时,不能使用实体类作为返回值,只能使用集合,否则会抛出异常
TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值
4.5 获取参数
MyBatis获取参数值的两种方式:${}和#{}
${}的本质就是字符串拼接,#{}的本质就是占位符赋值
${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自
动添加单引号
4.5.1若mapper接口中的方法参数为实体类对象时
此时可以使用KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{},通过访问实体类对象中的属…{}需要手动加单引号
4.5.2可以通过@Param注解标识mapper接口中的方法参数
此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值;以
param1,param2…为键,以参数为值;只需要通过KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{}访问map集合的键就可以获…{}需要手动加单引号
4.5.3若mapper接口中的方法参数为多个时
此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;以param1,param2…为键,以参数为值;因此只需要通过KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{}访问map集合的键就可以获…{}需要手动加单引号
4.6 resultMap处理字段和属性的映射关系
若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射
<!--
resultMap:设置自定义映射
属性:
id:表示自定义映射的唯一标识
type:查询的数据要映射的实体类的类型
子标签:
id:设置主键的映射关系
result:设置普通字段的映射关系
association:设置多对一的映射关系
collection:设置一对多的映射关系
属性:
property:设置映射关系中实体类中的属性名
column:设置映射关系中表中的字段名
-->
<resultMap id="userMap" type="User">
<id property="id" column="id"></id>
<result property="userName" column="user_name"></result>
<result property="password" column="password"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
</resultMap>
<!--List<User> testMohu(@Param("mohu") String mohu);-->
<select id="testMohu" resultMap="userMap">
<!--select * from t_user where username like '%${mohu}%'-->
select id,user_name,password,age,sex from t_user where user_name like
concat('%',#{mohu},'%')
</select>
若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性
名符合Java的规则(使用驼峰)
此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系
a>可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
b>可以在MyBatis的核心配置文件中设置一个全局配置信息mapUnderscoreToCamelCase,可
以在查询表中数据时,自动将_类型的字段名转换为驼峰
4.7 Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能.
4.7.1 IF标签
if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
<!--List<Emp> getEmpListByMoreTJ(Emp emp);-->
<select id="getEmpListByMoreTJ" resultType="Emp">
select * from t_emp where 1=1
<if test="ename != '' and ename != null">
and ename = #{ename}
</if>
<if test="age != '' and age != null">
and age = #{age}
</if>
<if test="sex != '' and sex != null">
and sex = #{sex}
</if>
</select>
4.7.2 where标签
a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and去掉
注意:where标签不能去掉条件最后多余的and
<select id="getEmpListByMoreTJ2" resultType="Emp">
select * from t_emp
<where>
<if test="ename != '' and ename != null">
ename = #{ename}
</if>
<if test="age != '' and age != null">
and age = #{age}
</if>
<if test="sex != '' and sex != null">
and sex = #{sex}
</if>
</where>
</select>
4.7.3
trim用于去掉或添加标签中的内容
常用属性:
prefix:在trim标签中的内容的前面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffix:在trim标签中的内容的后面添加某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容
<select id="getEmpListByMoreTJ" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and">
<if test="ename != '' and ename != null">
ename = #{ename} and
</if>
<if test="age != '' and age != null">
age = #{age} and
</if>
<if test="sex != '' and sex != null">
常用属性:
prefix:在trim标签中的内容的前面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffix:在trim标签中的内容的后面添加某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容
4、choose、when、otherwise
choose、when、otherwise相当于if...else if..else
5、foreach
sex = #{sex}
</if>
</trim>
</select>
4.7.4 foreach
属性:
collection:设置要循环的数组或集合
item:表示集合或数组中的每一个数据
separator:设置循环体之间的分隔符
open:设置foreach标签中的内容的开始符
close:设置foreach标签中的内容的结束符
<!--int insertMoreEmp(List<Emp> emps);-->
<insert id="insertMoreEmp">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.ename},#{emp.age},#{emp.sex},#{emp.email},null)
</foreach>
</insert>
<!--int deleteMoreByArray(int[] eids);-->
<delete id="deleteMoreByArray">
delete from t_emp where
<foreach collection="eids" item="eid" separator="or">
eid = #{eid}
</foreach>
五 Mybaits的缓存
5.1 一级缓存
一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就
会从缓存中直接获取,不会从数据库重新访问
使一级缓存失效的四种情况:
- 不同的SqlSession对应不同的一级缓存
- 同一个SqlSession但是查询条件不同
- 同一个SqlSession两次查询期间执行了任何一次增删改操作
- 同一个SqlSession两次查询期间手动清空了缓存
5.2 二级缓存
二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被
缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
二级缓存开启的条件:
a>在核心配置文件中,设置全局配置属性cacheEnabled=“true”,默认为true,不需要设置
b>在映射文件中设置标签
c>二级缓存必须在SqlSession关闭或提交之后有效
d>查询的数据所转换的实体类类型必须实现序列化的接口
使二级缓存失效的情况:
两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
5.3二级缓存的配置
在mapper配置文件中添加的cache标签可以设置一些属性:
eviction属性:缓存回收策略
LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。默认的是 LRU。
flushInterval属性:刷新间隔,单位毫秒默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
size属性:引用数目,正整数代表缓存最多可以存储多少个对象,太大容易导致内存溢出
readOnly属性:只读,true/false
true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。
false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false
5.4 MyBatis缓存查询的顺序
先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
如果二级缓存没有命中,再查询一级缓存如果一级缓存也没有命中,则查询数据库,SqlSession关闭之后,一级缓存中的数据会写入二级缓存
5.5通过第三方插件进行缓存EHCache
1.依赖
<!-- Mybatis EHCache整合包 -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<!-- slf4j日志门面的一个具体实现 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
2.配置文件
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!-- 磁盘保存路径 -->
<diskStore path="D:\atguigu\ehcache"/>
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
3.在mybatis里面配置
4.加入logback日志
存在SLF4J时,作为简易日志的log4j将失效,此时我们需要借助SLF4J的具体实现logback来打印日志。
创建logback的配置文件logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 日志输出的格式 -->
<!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -
->
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger]
[%msg]%n</pattern>
</encoder>
</appender>
<!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
<!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!-- 根据特殊需求指定局部日志级别 -->
<logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>
5.jar包的功能
六 MyBatis的逆向工程
6.1概述
正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程
的。
逆向工程:先创建数据库表,由框架负责根据数据库表生成实体类 以及映射接口和映射文件。
6.2创建逆向工程
6.2.1 添加依赖和插件(注意MySQL依赖)
<!-- 依赖MyBatis核心包 -->
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
</dependencies>
<!-- 控制Maven在构建过程中相关配置 -->
<build>
<!-- 构建过程中用到的插件 -->
<plugins>
<!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<!-- 插件的依赖 -->
<dependencies>
<!-- 逆向工程的核心依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
6.2.2 创建逆向工程的配置文件
文件名必须是:generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--
targetRuntime: 执行生成的逆向工程的版本
MyBatis3Simple: 生成基本的CRUD(清新简洁版)
MyBatis3: 生成带条件的CRUD(奢华尊享版)
-->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!-- 数据库的连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="123456">
</jdbcConnection>
<!-- javaBean的生成策略-->
<javaModelGenerator targetPackage="com.atguigu.mybatis.bean"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- SQL映射文件的生成策略 -->
<sqlMapGenerator targetPackage="com.atguigu.mybatis.mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- Mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.atguigu.mybatis.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 逆向分析的表 -->
<!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
<!-- domainObjectName属性指定生成出来的实体类的类名 -->
<table tableName="t_emp" domainObjectName="Emp"/>
<table tableName="t_dept" domainObjectName="Dept"/>
</context>
</generatorConfiguration>
6.2.3 双击执行插件
出现这张图片是配置成功
不成功就去看配置文件或者依赖
此时会有很多自动生成的方法
七 分页插件
7.1 配置插件
7.1 .1添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
7.1.2 在MyBatis的核心配置文件中配置插件
plugins>
<!--设置分页插件-->
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
7.2 使用插件
7.2.1在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能
pageNum:当前页的页码
pageSize:每页显示的条数
7.2.2在查询获取list集合之后,使用PageInfo pageInfo = new PageInfo<>(List list, intnavigatePages)获取分页相关数据
list:分页之后的数据
navigatePages:导航分页的页码数
分页相关数据
PageInfo{
pageNum=8, pageSize=4, size=2, startRow=29, endRow=30, total=30, pages=8,
list=Page{count=true, pageNum=8, pageSize=4, startRow=28, endRow=32, total=30,
pages=8, reasonable=false, pageSizeZero=false},
prePage=7, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true,
hasNextPage=false, navigatePages=5, navigateFirstPage4, navigateLastPage8,
navigatepageNums=[4, 5, 6, 7, 8]
}
7.2.3常用数据:
pageNum:当前页的页码
pageSize:每页显示的条数
size:当前页显示的真实条数
total:总记录数
pages:总页数
prePage:上一页的页码
nextPage:下一页的页码
isFirstPage/isLastPage:是否为第一页/最后一页
hasPreviousPage/hasNextPage:是否存在上一页/下一页
navigatePages:导航分页的页码数
navigatepageNums:导航分页的页码,[1,2,3,4,5]