Mybatis帮助文档
Maven仓库
三层架构
三层架构 (3-tier application) 通常意义上的三层架构就是将整个业务应用划分为:
表现层(UI)也叫界面层、业务逻辑层(BLL)、数据访问层(DAL)。区分层次的目的即为了“高内聚,低耦合”的思想。
1、表现层( User Interface):通俗讲就是展现给用户的界面,即用户在使用一个系统的时候他的所见所得。(jsp、html、servlet)
2、业务逻辑层( Business Logic Layer):针对具体问题的操作,也可以说是对数据层的操作,对数据业务逻辑处理。
3、数据访问层( Data Access Layer):该层所做事务直接操作数据库,针对数据的增添、删除、修改、更新、查找等。
三层对应的包
界面层: controller包 (servlet)
业务逻辑层: service 包(XXXService类)
数据访问层: dao包(XXXDao类)
三层中类的交互
用户使用界面层–> 业务逻辑层—>数据访问层(持久层)–>数据库(mysql)
三层对应的处理框架
界面层—servlet—springmvc(框架)
业务逻辑层—service类–spring(框架)
数据访问层—dao类–mybatis(框架)
Mybatis主要解决的问题:
减轻使用 JDBC 的复杂性,不用编写重复的创建 Connetion , Statement ; 不用编写关闭资源代码。 直接使用 java 对象,表示结果数据。让开发者专注 SQL 的处理。 其他分心的工作由 MyBatis 代劳。
Mybatis就是增强版的jdbc,让开发人员集中写sql
1、第一个mybatis程序
1.导入maven依赖
导入三个基本jar包 Connector Mybatis Junit
<!--导入依赖-->
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
//重要的,maven约定大于配置
//加如Maven插件
//静态过滤
<build>
<resources>
<resource>
<directory>src/main/resources</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
不然会出现以下问题
2.配置Mybatis核心文件
<?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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis
?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
//这里可能会出现数据库时区问题,win+r 设置 com.mysql.cj.jdbc.Driver 解决时区问题
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--告诉 mybatis 要执行的 sql 语句的位置-->
<mappers>
<mapper resource="com.cx.dao/UserMapper.xml"/>
</mappers>
</configuration>
3.编写Mybatis核心工具类
//SqlSessionFactory-->SqlSession工厂模式 生产它
public class MybatisUtils {
//加载资源
private static SqlSessionFactory sqlSessionFactory;
static {
//第一步:获取sqlSessionFactory对象
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取实例,包含了SQL所有方法(数据操作,增删改查)
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);//对象
}
}
4.编写接口实现类(DAO)
- 编写实体类
//快捷键 Alt+Ins
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
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;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
2.接口
public interface Usermapper {
List<User> getUserlist();
3.绑定接口
要求: 1. 在 dao 包中创建文件 UserDao.xml 2. 要 UserDao.xml 文件名称和接口 UserDao一样,区分大小写的一样。
<?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 接口的全限定名称
-->
<mapper namespace="com.cx.dao.UserDao">
<!--查询语句--><!--id对应对应方法名字-->
<!--
<select>: 查询数据, 标签中必须是 select 语句
id: sql 语句的自定义名称,推荐使用 dao 接口中方法名称,
使用名称表示要执行的 sql 语句
resultType: 查询语句的返回结果数据类型,使用全限定类名
-->
<select id="getUserList" resultType="pojo.User"><!--返回结果-->
<!--要执行的 sql 语句-->
select * from mybatis.user
</select>
</mapper>
5.配置日志功能
<!--mybatis.xml 文件加入日志配置,可以在控制台输出执行的 sql 语句和参数-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
6.编写测试类
public class UserDaoTest {
@Test
public void test(){
//获取 sqlSession方象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userlist = userDao.getUserlist();
for (User user : userlist) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
7.过程如下图:
2 、MyBatis 对象分析
1 .对象使用
SqlSession , SqlSessionFactory 等
(1) Resources 类
Resources 类,顾名思义就是资源,用于读取资源文件。其有很多方法通过加载并解析资源文件,返 回不同类型的 IO 流对象。
Resources.getResourceAsStream(config)
(2) SqlSessionFactoryBuilder 类
SqlSessionFactory 的 创 建 , 需 要 使 用 SqlSessionFactoryBuilder 对 象 的 build() 方 法 。 由 于 SqlSessionFactoryBuilder 对象在创建完工厂对象后,就完成了其历史使命,即可被销毁。所以,一般会将 该 SqlSessionFactoryBuilder 对象创建为一个方法内的局部对象,方法结束,对象销毁。
(3) SqlSessionFactory 接口
SqlSessionFactory 接口对象是一个**重量级对象(系统开销大的对象),是*线程安全的,所以一个应用只需要一个该对象***即可。创建 SqlSession 需要使用 SqlSessionFactory 接口的的 openSession()方法。
➢ openSession(true):创建一个有自动提交功能的 SqlSession
➢ openSession(false):创建一个非自动提交功能的 SqlSession,需手动提交
➢ openSession():同 openSession(false) 默认false
(4) SqlSession 接口
SqlSession 接口对象用于执行持久化操作。
一个 SqlSession 对应着一次数据库会话,一次会话以 SqlSession 对象的创建开始,以 SqlSession 对象的关闭结束。
*SqlSession 接口对象是线程不安全*的,所以每次数据库会话结束前,需要马上调用其 close()方法,将其关闭。**再次需要会话,再次创建。 SqlSession 在方法内部创建,使用完毕后关闭。
2.创建工具类
创建 MyBatisUtil 类
public class MybatisUtils {
//定义 SqlSessionFactory SqlSessionFactory 接口对象是一个重量级对象(系统开销大的对象),是线程安全的,所以一个应用只需要一个该对象即可
private static SqlSessionFactory factory = null;
//使用 静态块 创建一次 SqlSessionFactor
static {
//读取配置文件
String config="mybatis.xml";
try {
//创建 SqlSessionFactory 对象
InputStream in = Resources.getResourceAsStream(config);
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
// 获取SqlSession对象
public static SqlSession getSqlSession(){
SqlSession sqlSession=null;
if(factory != null){
sqlSession = factory.openSession();
}
return sqlSession ;
}
}
3、MyBatis 框架 Dao 代理
1.getMapper 获取代理对象
只需调用 SqlSession 的 getMapper()方法,即可获取指定接口的实现类对象。该方法的参数为指定 Dao 接口类的 Class 值。
SqlSession session = factory.openSession();
StudentDao dao = session.getMapper(StudentDao.class);
//使用工具类
StudentDao studentDao = MyBatisUtil.getSqlSession().getMapper(StudentDao.class);
2.使用 Dao 代理对象方法执行 sql 语句
//select 方法:
@Test
public void testSelect() throws IOException {
final List<Student> studentList = studentDao.selectStudents();
studentList.forEach( stu -> System.out.println(stu));
}
//insert 方法:
@Test
public void testInsert() throws IOException {
Student student = new Student();
student.setId(1006);
student.setName("林浩");
student.setEmail("linhao@163.com");
student.setAge(26);
int nums = studentDao.insertStudent(student);
System.out.println("使用 Dao 添加数据:"+nums);
}
//update 方法
@Test
public void testUpdate() throws IOException {
Student student = new Student();
student.setId(1006);
student.setAge(28);
int nums = studentDao.updateStudent(student);
System.out.println("使用 Dao 修改数据:"+nums);
}
//delete 方法
@Test
public void testDelete() throws IOException {
int nums = studentDao.deleteStudent(1006);
System.out.println("使用 Dao 修改数据:"+nums);
}
3.parameterType
parameterType: 接口中方法参数的类型, 类型的完全限定名或别名。
这个属性是可选的,因为 MyBatis 可以推断出具体传入语句的参数,默认值为未设置(unset)。
接口中方法的参数从 java 代码传入到 mapper 文件的 sql 语句。
int 或 java.lang.Integer hashmap
java.util.HashMap list 或 java.util.ArrayList student
<delete id="deleteStudent" parameterType="int">
delete from student where id=#{studentId}
</delete>
//等同于
<delete id="deleteStudent" parameterType="java.lang.Integer">
delete from student where id=#{studentId}
</delete>
4.MyBatis 传递参数
从 java 代码中把参数传递到 mapper.xml 文件。
5.一个简单参数
Dao 接口中方法的参数只有一个简单类型(java 基本类型和 String),占位符 #{ 任意字符 },和方法的参数名无关。
接口方法:
Student selectById(int id);
mapper 文件:
<select id="selectById" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
#{studentId} , studentId 是自定义的变量名称,和方法参数名无关。
测试方法:
@Test public void testSelectById()
//一个参数
Student student = studentDao.selectById(1005); System.out.println("查询 id 是 1005 的学生:"+student); }
6.多个参数-使用@Param
当 Dao 接口方法多个参数,需要通过名称使用参数。在方法形参前面加入@Param(“自定义参数名”), mapper 文件使用#{自定义参数名}。
例如定义
接口方法:
List<Student> selectMultiParam(@Param("personName") String name,
@Param("personAge") int age);
mapper 文件
<select id="selectMultiParam" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student where name=#{personName} or age
=#{personAge}
</select>
测试方法:
@Test
public void testSelectMultiParam(){
List stuList = studentDao.selectMultiParam("李力",20);
stuList.forEach( stu -> System.out.println(stu)); }
7.多个参数-使用对象
使用 java 对象传递参数, java 的属性值就是 sql 需要的参数值。
每一个属性就是一个参数。
语法格式: #{ property,javaType=java 中数据类型名,jdbcType=数据类型名称 }
javaType, jdbcType 的类型 MyBatis 可以检测出来,一般不需要设置。常用格式 #{ property }
创建保存参数值的对象 QueryParam
public class QueryParam
{
private String queryName;
private int queryAge;
//set ,get 方法
}
接口方法:
List<Student> selectMultiObject(QueryParam queryParam);
mapper 文件:
<select id="selectMultiObject" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student where name=#{queryName} or age
=#{queryAge}
</select>
或
<select id="selectMultiObject" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
where name=#{queryName,javaType=string,jdbcType=VARCHAR}
or age =#{queryAge,javaType=int,jdbcType=INTEGER}
</select>
测试方法:
@Test
public void selectMultiObject(){
QueryParam qp = new QueryParam();
qp.setQueryName("李力");
qp.setQueryAge(20);
List stuList = studentDao.selectMultiObject(qp);
stuList.forEach( stu -> System.out.println(stu)); }
8.#和$
#:占位符,告诉 mybatis 使用实际的参数值代替。并使用 PrepareStatement 对象执行 sql 语句, #{…}代替 sql 语句的“?”。这样做更安全,更迅速,通常也是首选做法,
mapper 文件
<select id="selectById" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
转为 MyBatis 的执行是:
String sql=” select id,name,email,age from student where id=?”;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1005);
解释: where id=? 就是 where id=#{studentId}
ps.setInt(1,1005) , 1005 会替换掉 #{studentId}
$ 字符串替换,告诉 mybatis 使用 包 含 的 “ 字 符 串 ” 替 换 所 在 位 置 。 使 用 S t a t e m e n t 把 s q l 语 句 和 包含的“字符串”替换所在位置。使用 Statement 把 sql 语句和 包含的“字符串”替换所在位置。使用Statement把sql语句和{}的 内容连接起来。主要用在替换表名,列名,不同列排序等操作。
例 1: 分别使用 id , email 列查询 Student 接口方法:
Student findById(int id);
Student findByEmail(String email);
mapper 文件:
<select id="findById" resultType="com.bjpowernode.domain.Student">
select * from student where id=#{studentId}
</select>
<select id="findByEmail" resultType="com.bjpowernode.domain.Student">
select * from student where email=#{stuentEmail}
</select>
测试方法:
@Test
public void testFindStuent(){
Student student1 = studentDao.findById(1002);
System.out.println("findById:"+student1);
Student student2 = studentDao.findByEmail("zhou@126.net");
System.out.println("findByEmail:"+student2);
}
例 2:通用方法,使用不同列作为查询条件
接口方法:
Student findByDiffField(@Param("col") String colunName,
@Param("cval") Object value);
mapper 文件:
<select id="findByDiffField" resultType="com.bjpowernode.domain.Student">
select * from student where ${col} = #{cval}
</select>
测试方法:
@Test
public void testFindDiffField(){
Student student1 = studentDao.findByDiffField("id",1002);
System.out.println("按 id 列查询:"+student1);
Student student2 = studentDao.findByDiffField("email","zhou@126.net");
System.out.println("按 email 列查询:"+student2);
}
9.封装 MyBatis 输出结果
9.1 resultType
resultType: 执行 sql 得到 ResultSet 转换的类型,使用类型的完全限定名或别名。 注意如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身。resultType 和 resultMap,不能同时使用
A、简单类型
接口方法:
int countStudent();
mapper 文件:
<select id="countStudent" resultType="int">
select count(*) from student
</select>
测试方法:
@Test
public void testRetunInt(){
int count = studentDao.countStudent();
System.out.println("学生总人数:"+ count); }
B、 对象类型
接口方法:
Student selectById(int id);
mapper 文件:
<select id="selectById" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
框架的处理: 使用构造方法创建对象。调用 setXXX 给属性赋值。 Student student = new Student();
注意:Dao 接口方法返回是集合类型,需要指定集合中的类型,不是集合本身。
C、 Map
sql 的查询结果作为 Map 的 key 和 value。推荐使用 Map.
注意:Map 作为接口返回值,sql 语句的查询结果最多只能有一条记录。大于一条记录是错误。
接口方法:
Map<Object object> selectReturnMap(int id);
mapper 文件:
<select id="selectReturnMap" resultType="java.util.HashMap">
select name,email from student where id = #{studentId}
</select>
测试方法:
@Test public void testReturnMap(){
Map retMap = studentDao.selectReturnMap(1002);
System.out.println("查询结果是 Map:"+retMap);
}
9.2 resultMap
resultMap 可以自定义 sql 的结果和 java 对象属性的映射关系。更灵活的把列值赋值给指定属性。 常用在列名和 java 对象属性名不一样的情况。
使用方式: 1.先定义 resultMap,指定列名和属性的对应关系。
2.在中把 resultType 替换为 resultMap。
接口方法:
List<Student> selectUseResultMap(QueryParam param);
mapper 文件:
<!-- 创建 resultMap
id:自定义的唯一名称,在<select>使用
type:期望转为的 java 对象的全限定名称或别名
-->
<!-- 主键字段使用 id -->
<id column="id" property="id" />
<!--非主键字段使用 result-->
<result column="name" property="name"/>
<result column="email" property="email" />
<result column="age" property="age" />
</resultMap>
<!--resultMap: resultMap 标签中的 id 属性值-->
<select id="selectUseResultMap" resultMap="studentMap">
<resultMap id="studentMap" type="com.bjpowernode.domain.Student"> select id,name,email,age from student where name=#{queryName} or age=#{queryAge}
</select>
测试方法:
@Test
public void testSelectUseDiffResultMap(){
QueryParam param = new QueryParam();
param.setQueryName("李力");
param.setQueryAge(20);
List<PrimaryStudent> stuList;
stuList = studentDao.selectUseDiffResultMap(param);
stuList.forEach( stu -> System.out.println(stu));
}
9.3 模糊查询 like
模糊查询的实现有两种方式, 一是 java 代码中给查询数据加上“%” ; 二是在 mapper 文件 sql 语句的条件位置加上“%” 需求:查询姓名有“力”的
例 1: java 代码中提供要查询的 “%力%”
接口方法:
List<Student> selectLikeFirst(String name);
mapper 文件
<select id="selectLikeFirst" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
where name like #{studentName}
</select>
测试方法:
@Test
public void testSelectLikeOne(){
String name="%力%";
List<Student> stuList = studentDao.selectLikeFirst(name);
stuList.forEach( stu -> System.out.println(stu));
}
例 2:mapper 文件中使用 like name “%” #{xxx} “%”
接口方法:
List<Student> selectLikeSecond(String name);
mapper 文件:
<select id="selectLikeSecond" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
where name like "%" #{studentName} "%"
</select>
测试方法:
@Test
public void testSelectLikeSecond(){
String name="力";
List<Student> stuList = studentDao.selectLikeSecond(name);
stuList.forEach( stu -> System.out.println(stu));
}
4、MyBatis 框架动态 SQL
动态 SQL 之
对于该标签的执行,当 test 的值为 true 时,会将其包含的 SQL 片断拼接到其所在的 SQL 语句中。
语法: sql 语句的部分
接口方法:
List<Student> selectStudentIf(Student student);
mapper 文件:
<select id="selectStudentIf" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
where 1=1
<if test="name != null and name !='' ">
and name = #{name}
</if>
<if test="age > 0 ">
and age > #{age}
</if>
</select>
测试方法:
@Test
public void testSelect() throws IOException {
Student param = new Student();
param.setName("李力");
param.setAge(18);
List studentList = studentDao.selectStudentIf(param);
studentList.forEach( stu -> System.out.println(stu));
}
动态 SQL 之
标签的中存在一个比较麻烦的地方:需要在 where 后手工添加 1=1 的子句。因为,若 where 后 的所有条件均为 false,而 where 后若又没有 1=1 子句,则 SQL 中就会只剩下一个空的 where,SQL 出错。所以,在 where 后,需要添加永为真子句 1=1,以防止这种情况的发生。但当数据量很大时,会 严重影响查询效率。
使用标签,在有查询条件时,可以自动添加上 where 子句;没有查询条件时,不会添加 where 子句。需要注意的是,第一个标签中的 SQL 片断,可以不包含 and。不过,写上 and 也不错, 系统会将多出的 and 去掉。但其它中 SQL 片断的 and,必须要求写上。否则 SQL 语句将拼接出错 。
语法: 其他动态语句sql
接口方法:
List<Student> selectStudentWhere(Student student);
mapper 文件:
<select id="selectStudentWhere" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
<where>
<if test="name != null and name !='' ">
and name = #{name}
</if>
<if test="age > 0 ">
and age > #{age}
</if>
</where>
</select>
测试方法:
@Test
public void testSelectWhere() throws IOException {
Student param = new Student();
param.setName("李力"); param.setAge(18);
List studentList = studentDao.selectStudentWhere(param);
studentList.forEach( stu -> System.out.println(stu));
}
动态 SQL 之
标签用于实现对于数组与集合的遍历。对其使用,需要注意:
➢ collection 表示要遍历的集合类型, list ,array 等。
➢ open、close、separator 为对遍历内容的 SQL 拼接。
语法:
<foreach collection="集合类型" open="开始的字符" close="结束的字符"
item="集合中的成员" separator="集合成员之间的分隔符">
#{item 的值}
</foreach>
<select id="selectForeachOne" resultType="com.cx.domain.Student">
select *from student where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
1) 遍历 List<简单类型>
表达式中的 List 使用 list 表示,其大小使用 list.size 表示。
需求:查询学生 id 是 1002,1005,1006
接口方法:
List<Student> selectStudentForList(List idList);
mapper 文件:
<select id="selectStudentForList"
resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
<if test="list !=null and list.size > 0 ">
where id in
<foreach collection="list" open="(" close=")"
item="stuid" separator=",">
#{stuid}
</foreach>
</if>
</select>
测试方法:
@Test
public void testSelectForList() {
List<Integer> list = new ArrayList<>();
list.add(1002);
list.add(1005);
list.add(1006);
List<Student> studentList = studentDao.selectStudentForList(list);
studentList.forEach( stu -> System.out.println(stu));
}
2) 遍历 List<对象类型>
接口方法:
List<Student> selectStudentForList2(List stuList);
mapper 文件:
<select id="selectStudentForList2"
resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
<if test="list !=null and list.size > 0 ">
where id in
<foreach collection="list" open="(" close=")"
item="stuobject" separator=",">
#{stuobject.id}
</foreach>
</if>
</select>
测试方法:
@Test
public void testSelectForList2() {
List<Student> list = new ArrayList<>();
Student s1 = new Student();
s1.setId(1002);
list.add(s1);
s1 = new Student();
s1.setId(1005);
list.add(s1);
List<Student> studentList = studentDao.selectStudentForList2(list);
studentList.forEach( stu -> System.out.println(stu));
}
动态 SQL 之代码片段
标签用于定义 SQL 片断,以便其它 SQL 标签复用。而其它标签使用该 SQL 片断,需要使用 子标签。该标签可以定义 SQL 语句中的任何部分,所以子标签可以放在动态 SQL 的任何位置。
接口方法:
List<Student> selectStudentSqlFragment(List stuList);
mapper 文件:
<!--创建 sql 片段 id:片段的自定义名称-->
<sql id="studentSql">
select id,name,email,age from student
</sql>
<select id="selectStudentSqlFragment"
resultType="com.bjpowernode.domain.Student">
<!-- 引用 sql 片段 -->
<include refid="studentSql"/>
<if test="list !=null and list.size > 0 ">
where id in
<foreach collection="list" open="(" close=")"
item="stuobject" separator=",">
#{stuobject.id}
</foreach>
</if>
</select>
测试方法:
@Test
public void testSelectSqlFragment() {
List<Student> list = new ArrayList<>();
Student s1 = new Student();
s1.setId(1002);
list.add(s1);
s1 = new Student();
s1.setId(1005);
list.add(s1);
List<Student> studentList = studentDao.selectStudentSqlFragment(list);
studentList.forEach( stu -> System.out.println(stu));
}
5、Mybatis 通用分页插件PageHelper
1.导入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
2.加入配置
//在<environments>之前加入
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>
3.PageHelper 对象
@Test
public void testSelect() throws IOException {
//获取第 1 页,3 条内容
PageHelper.startPage(1,3);
List<Student> studentList = studentDao.selectStudents();
studentList.forEach( stu -> System.out.println(stu));
}
d=“studentSql”/>
where id in
#{stuobject.id}
测试方法:
```java
@Test
public void testSelectSqlFragment() {
List<Student> list = new ArrayList<>();
Student s1 = new Student();
s1.setId(1002);
list.add(s1);
s1 = new Student();
s1.setId(1005);
list.add(s1);
List<Student> studentList = studentDao.selectStudentSqlFragment(list);
studentList.forEach( stu -> System.out.println(stu));
}
5、Mybatis 通用分页插件PageHelper
1.导入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
2.加入配置
//在<environments>之前加入
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>
3.PageHelper 对象
@Test
public void testSelect() throws IOException {
//获取第 1 页,3 条内容
PageHelper.startPage(1,3);
List<Student> studentList = studentDao.selectStudents();
studentList.forEach( stu -> System.out.println(stu));
}