mybatics
MyBatis
简介
- Mybatis是一款优秀的持久层框架,用于简化jdbc开发
- 持久层:
- 负责将数据保存到数据库的那一层代码
- javaEE三层架构:表现层、业务层、持久层
- 架构:
- 架构就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
- 在框架的基础之上构建软件编写更加高效、规范、通用、可拓展
现有的jdbc已经可以满足基本需求,为什么要用MyBatis
- jdbc的缺点
- 硬编码(就类似使用了字符串,如果需求发生变化,业务代码也需要变动):
- 注册驱动,获取连接
- SQL语句
- 解决方案:–>配置文件
- 操作繁琐
- 手动设置参数
- 手动封装结果集合
- 解决方案:–>自动完成
- 硬编码(就类似使用了字符串,如果需求发生变化,业务代码也需要变动):
- MyBatis几乎免除了所有的jdbc代码以及设置参数和获取结果集的工作
- MyBatis可以使后期维护成本大幅降低
MyBatis快速入门
查询user表中所有数据
- 创建user表,添加数据
create database mybatis;
use mybatis;drop table if exists tb_user;create table tb_user(id int primary key auto_increment,username varchar(20),password varchar(20),gender char(1),addr varchar(20)
);insert into tb_user values (1,'zhangsan','1234','男','北京'),(2,'lisi','234','女','天津'),(3,'wangwu','33','男','西安');
- 创建模块,导入坐标
<!-- 以下是需要添加的依赖-->
<dependencies><!-- mybatics依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.16</version></dependency><!-- mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><!-- Junit单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.5</version></dependency><!-- 添加sLf4j日志api--><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>2.0.16</version></dependency><!-- 添加logback-classic依赖--><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.5.11</version></dependency><!-- 添加Logback-core依赖--><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-core</artifactId><version>1.5.8</version></dependency></dependencies>
- 编写MyBatis核心配置文件 --> 替换连接信息,解决硬编码问题
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""https://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="zhangjiale"/><property name="password" value="159357258zx."/></dataSource></environment></environments><!-- sql映射文件的路径--><mappers><mapper resource="UserMapper.xml"/></mappers>
</configuration>
- 编写SQL映射文件 --> 统一管理sql语句,解决如硬编码问题
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace:名称空间
-->
<mapper namespace="test"><select id="selectAll" resultType="com.lele.pojo.User">select * from tb_user;</select>
</mapper>
- 编码
- 定义pojo中的User类
- 加载核心配置文件,获取SqlSessionFactory对象
- 获取SqlSession对象,执行sql语句
- 释放资源
核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3//EN""https://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=false"/><property name="username" value="zhangjiale"/><property name="password" value="159357258zx."/></dataSource></environment></environments><!-- sql映射文件的路径--><mappers><mapper resource="UserMapper.xml"/></mappers>
</configuration>
sql映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace:名称空间
-->
<mapper namespace="test"><select id="selectAll" resultType="com.lele.pojo.User">select * from tb_user;</select>
</mapper>
User类
package com.lele.pojo;// alt + 鼠标左键 :整列编写
public class User {private Integer id;private String username;private String password;private String gender;private String addr;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", gender='" + gender + '\'' +", addr='" + addr + '\'' +'}';}
}
MybatisDemo类
package com.lele;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;
import java.util.List;public class MybatisDemo {public static void main(String[] args) throws Exception {// 1. 加载mybatis的核心配置文件,获取SqlSessionFactory对象
// System.out.println(System.getProperty("user.dir"));String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 获取SqlSession对象,然后执行sql语句SqlSession sqlSession = sqlSessionFactory.openSession();List<Object> list = sqlSession.selectList("test.selectAll");System.out.println(list);}
}
Mapper代码开发
List<User> users = sqlSession.selextList("test.selectAll");
System.out.println(user);
上面的代码仍然存在硬编码问题–>“test.selectAll”
因此我们引入Mapper开发
- 解决原生方式中的硬编码
- 简化后期执行SQL
Mapper代理开发的问题
- 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
- 设置SQL应黑色文件的namespace属性为Mapper接口全限定名
- 在Mapper接口中定义方法,方法名就是SQL应黑色文件中sql语句的id,并保持参数类型和返回值类型一致
- 编码
- 通过SqlSession的getMapper方法获取Mapper接口的代理对象
- 调用对应方法完成sql的执行
- 细节:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式映射文件的加载
mybatis-config.xml --> 核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3//EN""https://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=false"/><property name="username" value="zhangjiale"/><property name="password" value="159357258zx."/></dataSource></environment></environments><mappers><!-- sql映射文件的路径--><mapper resource="com/lele/mapper/UserMapper.xml"/><!-- 将来会有各种各样的类,这样写还是比较麻烦,所以我们引入了包扫描的规则--><!-- mapper代理方式--><package name="com.lele.mapper"/></mappers>
</configuration>
UseMapper.xml -->映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace:名称空间
-->
<mapper namespace="com.lele.mapper.UserMapper"> <!-- 命令空间不能随便写,必须要对应接口的包路径--><select id="selectAll" resultType="com.lele.pojo.User">select * from tb_user;</select>
</mapper>
UserMapper接口
package com.lele.mapper;import com.lele.pojo.User;import java.util.List;public interface UserMapper {List<User> selectAll();
}
MybatisDemo2 -->具体调用类
package com.lele;import com.lele.mapper.UserMapper;
import com.lele.pojo.User;
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;
import java.util.List;public class MybatisDemo2 {public static void main(String[] args) throws Exception {// 1. 加载mybatis的核心配置文件,获取SqlSessionFactory对象
// System.out.println(System.getProperty("user.dir"));String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 获取SqlSession对象,然后执行sql语句SqlSession sqlSession = sqlSessionFactory.openSession();// List<Object> list = sqlSession.selectList("test.selectAll");UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> users = userMapper.selectAll();System.out.println(users);sqlSession.close();}
}
Mybatis核心配置文件
Mybatis核心配置文件的顶层结构如下:
-
configuration(配置)
- properites(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseldProvider(数据库厂商标识)
- mappers(映射器)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3//EN""https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><!-- 给类型起别名--><typeAliases><package name="com.lele.pojo"/></typeAliases><!--environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment--><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=false"/><property name="username" value="zhangjiale"/><property name="password" value="159357258zx."/></dataSource></environment></environments><mappers><!-- sql映射文件的路径--> <!-- <mapper resource="com/lele/mapper/UserMapper.xml"/>--><!-- 将来会有各种各样的类,这样写还是比较麻烦,所以我们引入了包扫描的规则--><!-- mapper代理方式--><package name="com.lele.mapper"/></mappers> </configuration>
Mybatis案例开发
MybatisX插件
- 一款基于IDEA的快速开发插件,为效率而生
- 主要功能
- XML和接口方法相互跳转
- 根据接口方法生成statement
查询所有数据
-
编写接口方法:Mapper接口
- 参数:无
- 结构:List
-
编写SQL语句:SQL映射文件:
-
执行方法,测试
其他都和前面差不多,下面是测试类MybatisTest
import com.lele.mapper.BrandMapper;
import com.lele.pojo.Brand;
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.InputStream;
import java.util.List;public class MybatisTest {@Testpublic void testSelectALl() throws Exception {// 1. 获取SqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();// 3. 获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// 4. 执行sql语句List<Brand> brands = brandMapper.selectAll();System.out.println(brands);// 5. 释放资源sqlSession.close();}
}
但是由于数据库表的字段名称 和 实体类的属性名称 不一样,则不能自动封装数据
解决方法:
mybatis-config核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace:名称空间
-->
<mapper namespace="com.lele.mapper.BrandMapper"> <!-- 命令空间不能随便写,必须要对应接口的包路径--><!--数据库的字段名称 和实体类的属性名称不一样,比如数据库的brand_name 和 实体类的brandName第一种方式: as起别名 :对不一样的列名起别名,让别名和实体类的属性名一样* 缺点:每次查询都要定义一次别名-->
<!-- <select id="selectAll" resultType="com.lele.pojo.Brand">-->
<!-- select id,brand_name as brandName ,company_name as companyName,ordered,description,status-->
<!-- from tb_rand;-->
<!-- </select>--><!--第二种方式:sql片段* 缺点:不够灵活-->
<!-- <sql id="brand_column">-->
<!-- id,brand_name as brandName ,company_name as companyName,ordered,description,status-->
<!-- </sql>-->
<!-- <select id="selectALl" resultType="brand">-->
<!-- select-->
<!-- <include refid="brand_column"></include>-->
<!-- from tb_rand-->
<!-- </select>--><!--第三种:resultMap1 定义<resultMap>标签2 在<select>标签中,将resultMap属性替换resultType属性--><!--id:唯一标识type: 映射类型--><resultMap id="brandResultMap" type="brand"><!--result:完成主键字段的映射column:列名property:实体类的属性名--><result column="brand_name" property="brandName"/><result column="company_name" property="companyName"/></resultMap><select id="selectAll" resultMap="brandResultMap">select *from tb_rand</select>
</mapper>
查询详情
首先BrandMapper接口里面定义了Brand selectById(int id);
然后再BrandMapper的xml文件里面添加
<select id="selectById" resultMap="brandResultMap">select *from tb_rand where id = #{id} </select>
然后就是测试函数那里修改了执行sql语句部分
@Testpublic void testSelectById() throws Exception {int id = 2;// 1. 获取SqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();// 3. 获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// 4. 执行sql语句Brand brand = brandMapper.selectById(id);System.out.println(brand);// 5. 释放资源sqlSession.close();}
条件查询
BrandMapper接口
package com.lele.mapper;import com.lele.pojo.Brand;
import org.apache.ibatis.annotations.Param;import java.util.List;
import java.util.Map;public interface BrandMapper {List<Brand> selectAll();Brand selectById(int id);/*** 条件参数* 参数接收* * 散装参数: 如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")* * 对象参数: 对象的属性名称要和参数名称一致* * map集合参数** @param status* @param brandName* @param companyName* @return*/// List<Brand> selectByCondition(@Param("status") int status,
// @Param("brandName") String brandName,
// @Param("companyName") String companyName);// List<Brand> selectByCondition(Brand brand);List<Brand> selectByCondition(Map map);
}
BrandMapper.xml
package com.lele.mapper;import com.lele.pojo.Brand;
import org.apache.ibatis.annotations.Param;import java.util.List;
import java.util.Map;public interface BrandMapper {List<Brand> selectAll();Brand selectById(int id);/*** 条件参数* 参数接收* * 散装参数: 如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")* * 对象参数: 对象的属性名称要和参数名称一致* * map集合参数** @param status* @param brandName* @param companyName* @return*/// List<Brand> selectByCondition(@Param("status") int status,
// @Param("brandName") String brandName,
// @Param("companyName") String companyName);// List<Brand> selectByCondition(Brand brand);List<Brand> selectByCondition(Map map);
}
测试方法
@Test // 散装参数public void testSelectByCondition() throws Exception {int status = 1;String companyName = "华为";String brandName = "华为";//模糊查询companyName = "%" + companyName + "%";brandName = "%" + brandName + "%";// 使用对象参数
// Brand brand = new Brand();
// brand.setCompanyName(companyName);
// brand.setBrandName(brandName);
// brand.setStatus(status);// 使用Map参数Map map = new HashMap();map.put("status", status);map.put("companyName", companyName);map.put("brandName", brandName);// 1. 获取SqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();// 3. 获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// 4. 执行sql语句//List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);//List<Brand> brands = brandMapper.selectByCondition(brand);List<Brand> brands = brandMapper.selectByCondition(brand);System.out.println(brands);// 5. 释放资源sqlSession.close();}
经过上面的代码,我们能够实现查询,但是每次查询必须要求三个参数都存在,但实际生活中我们可能只想要通过某一个进行查询,也就是说上面的程序不灵活,所以就引出了接下来的动态条件查询
动态条件查询
多条件 -- 同态条件查询
动态SQL:
- if: 用于判断参数是否优质,使用test属性进行条件判断
- 存在的问题:第一个条件不需要逻辑运算符
- 解决方案:
- 恒等式
- 标签
<select id="selectByCondition" resultMap="brandResultMap">select *from tb_rand<where><if test="status != null">and status=#{status}</if><if test="companyName != null and companyName != ''">and company_name like #{companyName}</if><if test="brandName != null and brandName != ''">and brand_name like #{brandName}</if></where></select>
单条件 -- 动态查询
单条件或者没有条件
- 单条件: choose标签
- 无条件: otherwise标签+恒等式 或者 将choose标签写进where标签里面
<!--单条件或者没有条件单条件: choose标签无条件: otherwise标签+恒等式 或者将choose标签写进where标签里面--><select id="selectByConditionSingle" resultMap="brandResultMap">select *from tb_randwhere<choose> <!-- 相当于switch--><when test="status != null"> <!-- 相当于case-->status = #{ststus}</when><when test="companyName != null and companyName != ''">company_name like #{companyName}</when><when test="brandName != null and brandName != ''">brand_name like #{brandName}</when><otherwise> <!-- 相当于default,保底方案-->1 = 1</otherwise></choose></select><select id="selectByConditionSingle" resultMap="brandResultMap">select *from tb_rand<where><choose> <!-- 相当于switch--><when test="status != null"> <!-- 相当于case-->status = #{ststus}</when><when test="companyName != null and companyName != ''">company_name like #{companyName}</when><when test="brandName != null and brandName != ''">brand_name like #{brandName}</when><otherwise> <!-- 相当于default,保底方案-->1 = 1</otherwise></choose></where></select>
测试类
@Test // 散装参数public void testSelectByConditionSinglr() throws Exception {int status = 1;String companyName = "华为";String brandName = "华为";//模糊查询companyName = "%" + companyName + "%";brandName = "%" + brandName + "%";// 使用对象参数Brand brand = new Brand();brand.setCompanyName(companyName);//brand.setBrandName(brandName);//brand.setStatus(status);// 1. 获取SqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();// 3. 获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// 4. 执行sql语句//List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);//List<Brand> brands = brandMapper.selectByCondition(brand);List<Brand> brands = brandMapper.selectByConditionSingle(brand);System.out.println(brands);// 5. 释放资源sqlSession.close();}
添加
基础添加
- 编写接口方法:Mapper接口
- 参数:除了id之外的所有数据
- 结果:void
- 编写SQL语句:SQL映射文件
<insert id="add">insert into tb_rand(brand_name,company_name,ordered,description,ststus)value(#{brandName},#{companyName},#{ordered},#{description},#{status})
</insert>
- 执行方法,测试
- MyBatis事务
- openSession():默认开启事务,进行增删改之后需要使用sqlSession.commit()提交事务
- openSession(true):可以设置为自动提交事务
- MyBatis事务
添加 -- 主键返回
上面代码虽然能够正确添加数据,id的值是获取不出来的,因此可能会引出一些问题
我们只需要在对应的xml文件里面添加两个参数即可
<insert id="testAdd" useGeneratedKeys="true" keyProperty="id">insert intotb_rand(brand_name,company_name,ordered,description,status)value(#{brandName},#{companyName},#{ordered},#{description},#{status})</insert>
useGeneratedKeys="true" keyProperty="id"
修改
修改全部字段
- 编写Mapper接口
- 参数:所有数据
- void
- 编写Sql语句,sql映射文件
- 执行方法,测试
添加一个int update(Brand brand);
类中的方法
BrandMapper.xml中的添加
<update id="update">update tb_randsetbrand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status}where id = #{id}</update>
测试类添加了一个方法
@Test // 散装参数public void testUpdate() throws Exception {int status = 1;String companyName = "波导打飞机";String brandName = "波导哇哈哈";String desription = "手机中的战斗机";int ordered = 100;int id = 4;//模糊查询
// companyName = "%" + companyName + "%";
// brandName = "%" + brandName + "%";// 使用对象参数Brand brand = new Brand();brand.setCompanyName(companyName);brand.setBrandName(brandName);brand.setStatus(status);brand.setDescription(desription);brand.setOrdered(ordered);brand.setId(id);// 1. 获取SqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);// 3. 获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// 4. 执行sql语句int count = brandMapper.update(brand);System.out.println(count);// 5. 释放资源// 如果没有提交,因为默认开启的时候设置的为开启事务但不自动提交,所以事务回滚导致添加失败但不报错//sqlSession.commit();// 如果不想手动设置关闭事务sqlSession.close();}
修改动态字段
这个就是修改的时候不固定,也就是sql语句不能写死,要用动态sql去写
<update id="update">update tb_rand<set><if test="brandName != null and brandName != ''">brand_name = #{brandName},</if><if test="companyName != null and companyName != ''">company_name = #{companyName},</if><if test="ordered != null">ordered = #{ordered},</if><if test="description != null and description != ''">description = #{description},</if><if test="status != null">status = #{status}</if>where id = #{id}</set></update>
测试方法不用变,这样就可以动态的设置属性,可以不一次性全部注入
删除
删除一个
BrandMapper类中添加方法void deleteById(int id);
BrandMapper.xml中添加对应的映射
<delete id="deleteById">delete from tb_randwhere id = #{id}</delete>
测试类中添加方法
@Test // 散装参数public void testDeleteById() throws Exception {int id = 4;// 1. 获取SqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);// 3. 获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// 4. 执行sql语句brandMapper.deleteById(id);// 5. 释放资源// 如果没有提交,因为默认开启的时候设置的为开启事务但不自动提交,所以事务回滚导致添加失败但不报错//sqlSession.commit();// 如果不想手动设置关闭事务sqlSession.close();}
批量删除
mybatis会将参数数组,封装为一个Map集合
- 默认 :array = key
* 使用@Param注解改变map集合的默认的key名称
BrandMapper类中添加方法void deleteByIds(@Param("ids")int[] ids)
BrandMapper.xml中添加对应的映射
<!--mybatis会将参数数组,封装为一个Map集合* 默认 :array = key* 使用@Param注解改变map集合的默认的key名称--><delete id="deleteByIds">delete from tb_randwhere id in (<foreach collection="ids" item="id" separator=",">#{id}</foreach>);</delete>
测试类中添加方法
@Test // 散装参数public void testDeleteByIds() throws Exception {int[] ids = {1,2,3};// 1. 获取SqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);// 3. 获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// 4. 执行sql语句brandMapper.deleteByIds(ids);// 5. 释放资源// 如果没有提交,因为默认开启的时候设置的为开启事务但不自动提交,所以事务回滚导致添加失败但不报错//sqlSession.commit();// 如果不想手动设置关闭事务sqlSession.close();}
MyBatis参数传递
MyBatis提供了ParamNameResolver类来进行参数封装
MyBatis接口方法中可以接收各种各样的参数,Mybatis底层对于这些参数进行了不同的封装处理方式
单个参数:
-
POJO类型: 直接使用,属性名 和 参数占位符名称一致
-
Map集合: 直接使用,键名 和 参数占位符名称一致
-
Collection: 封装为Map集合
- map.put(“arg0”,collection集合)
- map.put(“collection”,collection集合)
-
List
- map.put(“arg0”,list集合)
- map.put(“collection”,list集合)
- map.put(“list”,list集合)
-
Array: 封装为Map集合
- map.put(“arg0”,数组)
- map.put(“array”,数组)
-
其他类型 直接使用
多个参数:封装为Map集合,默认的是[arg0,arg1或者param1,param2],一个参数对应两个不同的键
可以使用@Param注解,替换Map集合中默认的键名
- map.put(“arg0”,参数值1)
- map.put(“param”,参数值1)
- map.put(“param2”,参数值2)
- map.put(“arg1”,参数值2)
注解开发
使用注解开发回避配置文件更加方便
- 查询:@Select
- 添加: @Insert
- 修改: @Modify
- 删除: @Delete
提示:
- 注解完成简单功能
- 配置文件完成复杂功能
UserMapper类
public interface UserMapper {@Select("select * from tb_user where id = #{}")List<User> selectAll();
}
其他代码均不变,仍可正常执行