一、获取MyBatis
-
maven仓库:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>x.x.x</version> </dependency>
-
Github:https://github.com/mybatis/mybatis-3/releases
-
中文文档:https://mybatis.net.cn/getting-started.html
二、环境搭建
1.数据库搭建
CREATE TABLE `user` (
`id` INT ( 20 ) NOT NULL PRIMARY KEY,
`name` VARCHAR ( 30 ) DEFAULT NULL,
`pwd` VARCHAR ( 30 ) DEFAULT NULL
) ENGINE = INNODB DEFAULT charset = utf8
insert into `user` (`id`,`name`,`pwd`) values
(1,'chenyu','123456'),
(2,'cy','123456'),
(3,'admin','123456')
2.新建Maven项目
删除src文件夹,编写父项目的pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 父工程 -->
<groupId>org.example</groupId>
<artifactId>myBatis</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 导入依赖 -->
<dependencies>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.创建一个模块
- 编写核心配置文件 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.jdbc.Driver"/>
<!-- 高版本 -->
<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&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写mybatis工具类
package com.chen.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SQL;
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;
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 使用Mybatis第一步:获取sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例
// SqlSession 完全包含了面向数据库执行SQL命令所需的所有方法。
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
4.编写代码
- 实体类(pojo)
package com.chen.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
- Dao接口(dao)
package com.chen.mapper;
import com.chen.pojo.User;
import java.util.List;
public interface userMapper {
List<User> getUserList();
}
- 接口实现类(Mapper.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">
<!-- namespace=绑定一个对应的Dao或者Mapper接口-->
<mapper namespace="com.chen.mapper.UserMapper">
<!-- 查询语句 -->
<!-- id=方法名 -->
<select id="getUserList" resultType="com.chen.pojo.User">
select * from mybatis.user
</select>
</mapper>
5.测试
在src/test/java里面创建测试类
package com.chen.dao;
import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test() {
// 1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
// 方式一:getMapper
// 2.获得Mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 3.执行SQL
List<User> userList = mapper.getUserList();
// 方式二:
// List<User> userList = sqlSession.selectList("com.chen.mapper.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 4.关闭SqlSession
sqlSession.close();
}
}
}
注意点:绑定异常
org.apache.ibatis.binding.BindingException:
Type interface com.chen.mapper.UserMapper is not known to the MapperRegistry.
MapperRegistry 不知道类型接口 com.chen.mapper.UserMapper。
解决方法:mybatis-config.xml中注册Mapper
<!-- 每一个Mapper.XML都需要在Mybatis核心配置文件注册 -->
<mappers>
<mapper resource="com/chen/mapper/UserMapper.xml"/>
</mappers>
注册了但是扫描不到mapper的文件需要在配置文件中添加扫描配置
解决方法:pom.xml增加配置
<!-- 添加扫描配置 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<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>
<!-- UTF-8配置问题 -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
三、SQL基本操作
1.namespace
namespace中的包名要和Dao/mapper接口包名一致
2.select
选择,查询语句;
- id:对应namespace接口中的方法名
- parameterType:参数类型
- resultType:返回值类型,可以是class也可以是基本数据类型。
3.Insert
<insert id="addUser" parameterType="com.chen.pojo.User">
insert into mybatis.user (id,name,pwd) value (#{id},#{name},#{pwd});
</insert>
4.Update
<update id="updateUser" parameterType="com.chen.pojo.User">
update mybatis.user
set name = #{name},pwd = #{pwd}
where id = #{id};
</update>
5.Delete
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from mybatis.user where id = #{id}
</delete>
6.测试
注意:增删改需要提交事务,否则所做操作无效
package com.chen.dao;
import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
import java.util.Scanner;
public class UserMapperTest {
@Test
public void test() {
// 1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
// 方式一:getMapper
// 2.获得Mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 3.执行SQL
List<User> userList = mapper.getUserList();
// 方式二:
// List<User> userList = sqlSession.selectList("com.chen.mapper.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 4.关闭SqlSession
sqlSession.close();
}
}
@Test
public void testGetUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user.toString());
sqlSession.close();
}
@Test
public void testAddUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.addUser(new User(5, "zhang", "123456"));
if (row > 0) {
System.out.println("增加成功!");
}
sqlSession.commit();
sqlSession.close();
this.test();
}
@Test
public void testUpdateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.updateUser(new User(2, "chen", "123456"));
if (row > 0) {
System.out.println("修改成功!");
}
sqlSession.commit();
this.test();
}
@Test
public void testDeleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.deleteUser(1);
if (row > 0) {
System.out.println("删除成功!");
}
sqlSession.commit();
this.test();
}
}
四、SQL进阶操作
1.万能Map
好处:不受字段限制就能进行数据操作
/**
* 根据条件Map获取用户
* @param map 条件
* @return 用户
*/
List<User> getUserByMap(Map<String,Object> map);
<select id="getUserByMap" parameterType="map" resultType="com.chen.pojo.User">
select * from mybatis.user
<where>
<if test="userId!=null">
id = #{userId}
</if>
<if test="userName != null">
and name like "%"#{userName}"%"
</if>
<if test="userPassword != null">
and pwd = #{userPassword}
</if>
</where>
</select>
@Test
public void testGetUserByMap() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userPassword", "123456");
map.put("userName", "z");
List<User> userList = mapper.getUserByMap(map);
System.out.println(userList.toString());
sqlSession.close();
}
2.模糊查询
方式一:写死,好处是用户不能随便进行更多操作
name like "%"#{userName}"%"
方式二:放开,用户可以通过不同的字符集进行不同的操作效果
map.put("userName", "%z%");
name like #{userName}
3.#{}使用
- MyBatis处理 #{ } 占位符,使用的 JDBC 对象是 PreparedStatement 对象,执行sql语句的效率更高。
- 使用 PreparedStatement 对象,能够避免 sql 注入,使得sql语句的执行更加安全。
- #{ } 常常作为列值使用,位于sql语句中等号的右侧;
- #{ } 位置的值与数据类型是相关的。
4.${}使用
- MyBatis处理 ${ } 占位符,执行sql语句的效率相对于 #{ } 占位符要更低。
- ${ } 占位符的值,使用的是字符串连接的方式,有 sql 注入的风险,同时也存在代码安全的问题。
- ${ } 占位符中的数据是原模原样的,不会区分数据类型。
- ${ } 占位符常用作表名或列名,这里推荐在能保证数据安全的情况下使用 ${ }。
/**
* 自定义获取User
* @return 用户集合
*/
List<User> getUserWhere(String where);
<select id="getUserWhere" resultType="com.chen.pojo.User">
select *
from mybatis.user
where ${where}
</select>
@Test
public void testGetUserWhere() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserWhere("id = 1");
System.out.println(userList.toString());
sqlSession.close();
}
5.结果集映射ResultMap
当数据库字段名与实体对象不匹配时,我们用到结果集映射来将数据库字段名与实体对象名关联匹配。
id name pwd
id name password
<!-- 结果集映射 -->
<resultMap id="UserMap" type="User">
<!-- column:数据库列 property:实体属性 -->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select *
from mybatis.user
where id = #{id}
</select>
也可以简单写成只映射数据库中对应字段不一样的做映射
<!-- 结果集映射 -->
<resultMap id="UserMap" type="User">
<!-- column:数据库列 property:实体属性 -->
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select *
from mybatis.user
where id = #{id}
</select>
6.分页
Mappser.xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select *
from mybatis.user
limit #{pageNo},#{pageSize}
</select>
Mapper.java
List<User> getUserByLimit(Map<String, Integer> map);
调用
@Test
public void testLimit() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("pageNo", 0);
map.put("pageSize", 2);
List<User> list = mapper.getUserByLimit(map);
for (User user : list) {
logger.info(user.toString());
}
sqlSession.close();
}
五、注解开发
使用注解可以简化对Mapper.xml文件的操作
1.基础使用
mapper层
@Select("select * from user")
List<User> getUserList();
调用
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
System.out.println(userList.toString());
sqlSession.close();
}
2.查
mapper
// 方法存在多个参数,所有参数前面加上@Param
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
调用
@Test
public void testGetUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user.toString());
sqlSession.close();
}
3.增
mapper
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password}) ")
int addUser(User user);
调用
@Test
public void testAdd(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(6, "huang", "123456");
mapper.addUser(user);
// 在构造时候传参可以无需提交事务
sqlSession.close();
}
4.改
mapper
@Update("update user set name=#{name},pwd=#{password} where id = #{id}")
int updateUser(User user);
调用
@Test
public void testUpdate(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(7, "yue", "654321"));
sqlSession.close();
}
5.删
mapper
@Delete("delete from user where id = #{id}")
int delUser(@Param("id") int id);
调用
@Test
public void testDelete(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delUser(7);
sqlSession.close();
}
6.lombok
简化实体对象操作
-
需要idea增加插件"lombok"
-
需要导包
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> <scope>provided</scope> </dependency>
使用
@Alias("User")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
- @Data:无参构造方法、get、set、toString
- @AllArgsConstructor:所有参数构造
- @NoArgsConstructor:无参构造
六、多表操作
1.准备部分
创建老师表
CREATE TABLE `teacher` (
`id` int(10) NOT NULL,
`name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO teacher(`id`,`name`) VALUES (1,'陈老师');
创建学生表
CREATE TABLE student(
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid`(`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student`(`id`,`name`,`tid`)
VALUES
('1','小张','1'),
('2','小周','1'),
('3','小黄','1'),
('4','小田','1'),
('5','小欧','1'),
('6','小曹','1'),
('7','小李','1');
2.多对一处理
目的:查询多个学生所对应的老师
方式一:子查询
mapper.java
List<Student> getStudentList();
mapper.xml
<resultMap id="StudentTeacher" type="Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
<!-- 复杂属性需要单独处理
1.对象使用association
2.集合使用collection
-->
<association column="tid" property="teacher" javaType="Teacher" select="getTeacher"/>
</resultMap>
<!-- 根据id -->
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{id}
</select>
<select id="getStudentList" resultMap="StudentTeacher">
select * from mybatis.student
</select>
将查出学生的结果再通过子查询形式查到对应老师
方式二:按照结果嵌套处理
<select id="getStudentList2" resultMap="StudentTeacher2">
select s.id sid,
s.name sname,
t.id tid,
t.name tname
from mybatis.student as s,
mybatis.teacher as t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
3.一对多处理
方式一:按结果集嵌套
<resultMap id="TeacherStudent" type="Teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
<!--
javaType:指定的类型
ofType:集合中的泛型信息
-->
<collection
property="studentList"
ofType="Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname, t.id tid
from mybatis.teacher as t,
mybatis.student as s
where s.tid = t.id
and t.id = #{id}
</select>
方式二:子查询
<select id="getTeacher2" resultMap="TeacherStudent2">
select *
from mybatis.teacher
where id = #{id}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection
property="studentList"
javaType="ArrayList"
ofType="Student"
select="getStudentByTeacherId"
column="id"
/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select *
from mybatis.student
where tid = ${id}
</select>
4.小结
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaType:java中对应的实体类型
- ofType:集合中的实体类型
七、动态SQL
1.准备部分
创建表
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建实体
@Data
@Alias("Blog")
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
2.where,if
if:条件执行
where:去掉第一个查询条件的AND 或 OR ,没有条件匹配去除where
mapper.java
List<Blog> getBlogIf(Map map);
mapper.xml
<select id="getBlogIf" parameterType="Blog" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
AND author = #{author}
</if>
</where>
</select>
test.java
@Test
public void getBlogIf() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, String> map = new HashMap<String, String>();
map.put("title", "Mybatis如此简单");
List<Blog> blogIf = mapper.getBlogIf(map);
for (Blog blog : blogIf) {
System.out.println(blog);
}
sqlSession.close();
}
3.choose,when,otherwise
choose:唯一满足条件查询
when:条件
otherwise:无匹配条件执行
mappper.java
List<Blog> queryBlogChoose(Map map);
mapper.xml
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views > 1000
</otherwise>
</choose>
</where>
</select>
test.java
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, String> map = new HashMap<String, String>();
// map.put("title", "Java如此简单");
map.put("author", "chen");
List<Blog> blogIf = mapper.queryBlogChoose(map);
for (Blog blog : blogIf) {
System.out.println(blog);
}
sqlSession.close();
}
4.set
set:自动去除结尾","
mapper.java
int updateBlog(Blog blog);
mapper.xml
<update id="updateBlog" parameterType="Blog">
update mybatis.blog
<set>
<if test="title != null">
title=#{title},
</if>
<if test="author != null">
author=#{author},
</if>
</set>
where id=#{id}
</update>
test.java
@Test
public void updateTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId("7b680cce1ccf483e8ebb155eb2b455b8");
blog.setAuthor("yu");
mapper.updateBlog(blog);
sqlSession.commit();
sqlSession.close();
}
5.trim
prefix:添加前缀 WHERE 或 SET 以及 “(”
suffix:添加后缀 “)”
prefixOverrides:要去除的前缀 “AND | OR”
suffixOverrides:要去除的后缀","
6.SQL片段
将可复用的SQL片段提取出来
1.使用sql标签提取出复用部分
2.使用include标签包含复用部分
注意:最好基于单表来定义SQL片段,不要包含where 和set标签
<sql id="if-title-author">
<if test="title != null">
title=#{title},
</if>
<if test="author != null">
author=#{author},
</if>
</sql>
<update id="updateBlog" parameterType="Blog">
update mybatis.blog
<set>
<include refid="if-title-author"></include>
</set>
where id=#{id}
</update>
7.foreach
collection:集合
item:单个对象
index:下标
open:开始符号
separator:间隔符号
close:结束符号
案例:批量新增
mapper.java
int addBlogBatch(@Param("list") List<Blog> list);
mapper.xml
<insert id="addBlogBatch" parameterType="list">
insert into mybatis.blog(id, title, author, create_time, views)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id}, #{item.title}, #{item.author}, #{item.createTime}, #{item.views})
</foreach>
</insert>
test.java
@Test
public void addBatch() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
ArrayList<Blog> list = new ArrayList<Blog>();
for (int i = 1; i <= 5; i++) {
Blog blog = new Blog();
blog.setId(IdUtils.getId());
blog.setTitle("标题" + i);
blog.setAuthor("作者" + i);
blog.setViews(i);
blog.setCreateTime(new Date());
list.add(blog);
}
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
mapper.addBlogBatch(list);
sqlSession.commit();
sqlSession.close();
}
/set>
where id=#{id}
### 7.foreach
**collection**:集合
**item**:单个对象
**index**:下标
**open**:开始符号
**separator**:间隔符号
**close**:结束符号
案例:批量新增
mapper.java
```java
int addBlogBatch(@Param("list") List<Blog> list);
mapper.xml
<insert id="addBlogBatch" parameterType="list">
insert into mybatis.blog(id, title, author, create_time, views)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id}, #{item.title}, #{item.author}, #{item.createTime}, #{item.views})
</foreach>
</insert>
test.java
@Test
public void addBatch() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
ArrayList<Blog> list = new ArrayList<Blog>();
for (int i = 1; i <= 5; i++) {
Blog blog = new Blog();
blog.setId(IdUtils.getId());
blog.setTitle("标题" + i);
blog.setAuthor("作者" + i);
blog.setViews(i);
blog.setCreateTime(new Date());
list.add(blog);
}
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
mapper.addBlogBatch(list);
sqlSession.commit();
sqlSession.close();
}