Mybatis - MyBatis完成增删改查详细案例
作者:互联网
文章目录
MyBatis核心配置文件
直接看案例xml文件
mybatis-config.xml 中的enviroment
<!--
environments:配置数据库连接环境信息,可以配置多个enviroment,通过default属性切换不同的
-->
<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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="12345"/>
</dataSource>
</environment>
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="12345"/>
</dataSource>
</environment>
</environments>
别名方式配置(包扫描)
<typeAliases>
<package name="com.taotao.pojo"/>
</typeAliases>
写完后我们可以在resultType里面直接传入类,比如“user”
改之前
Tb_userMapper.xml
<!--statement-->
<select id="selectAll" resultType="com.taotao.pojo.Tb_user">
select * from tb_user;
</select>
用别名方式后
Tb_userMapper.xml
<!--statement-->
<select id="selectAll" resultType="user">
select * from tb_user;
</select>
配置文件完成增删改查
准备环境
数据库表tb_brand
在mybatis数据库中创建
drop table if exists tb_brand;
create table tb_brand
(
id int primary key auto_increment,
brand_name varchar(20),
company_name varchar(20),
ordered int,
description varchar(100),
status int
);
insert into tb_brand (brand_name,company_name,ordered,description,status)
values('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0),
('华为','华为技术有限公司',100,'华为致力于把数字世界带入每个人,每个家庭,每个组织,构建万物互联的智能世界',1),
('小米','小米科技有限公司',50,'are you ok',1);
select * from tb_brand;
实体类Brand
我们在pojo包下新建Brand实体类
package com.taotao.pojo;
public class Brand {
private Integer id;
private String brand_name;
private String company_name;
private Integer ordered;
private String description;
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brand_name='" + brand_name + ''' +
", company_name='" + company_name + ''' +
", ordered=" + ordered +
", description='" + description + ''' +
", status=" + status +
'}';
}
}
测试用例
我们在maven项目test目录下的java目录下创建测试包
安装MyBatisX插件
插件介绍
- MybatisX是一款基于 IDEA的快速开发插件,为效率而生
- 主要功能
- XML 和 接口方法 相互跳转
- 根据接口方法生成 statement
举例
使用方法(点击鸟跳转)
一.查询
查询所有数据
- 编写接口方法:Mapper接口
- 参数:无
- 结果:List< brand >
- 编写SQL语句:SQL映射文件
- 执行方法,测试
编写接口方法
package com.taotao.mapper;
import com.taotao.pojo.Brand;
import java.util.List;
@SuppressWarnings({"all"})
public interface BrandMapper {
/**
* * 查询所有
*/
public List<Brand> selectAll();
}
编写BrandMapper.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:名称空间-->
<!--statement-->
<mapper namespace="com.taotao.mapper.BrandMapper">
</mapper>
写到这里我们可以刷新连接下数据库,为了方便提示信息
出现提示,我们继续往下走(需要设置setting-sql dialects)
我们编写test包里的MyBatisTest
package com.taotao.test;
import com.taotao.mapper.BrandMapper;
import com.taotao.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.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void testSelectAll() throws IOException {
//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.执行方法
List<Brand> brands = brandMapper.selectAll();
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
}
我们更改加载sql文件映射
运行成功
起别名
起别名:对不一样的列名起别名,让别名和实体类的属性名一样
快捷录入
<?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:名称空间-->
<!--statement-->
<mapper namespace="com.taotao.mapper.BrandMapper">
<!--
数据库的字段名称 和 实体类的属性名称不一样,则不能自动封装数据
*起别名:对不一样的列名起别名,让别名和实体类的属性名一样
*缺点:每次查询都要定义一次别名
-->
<select id="selectAll" resultType="brand">
select id, brand_name as brandName, company_name as companyName,
ordered, description, status
from tb_brand;
</select>
</mapper>
sql片段
<?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:名称空间-->
<!--statement-->
<mapper namespace="com.taotao.mapper.BrandMapper">
<!--
数据库的字段名称 和 实体类的属性名称不一样,则不能自动封装数据
*起别名:对不一样的列名起别名,让别名和实体类的属性名一样
*缺点:每次查询都要定义一次别名
-->
<!-- 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"/>
from tb_brand;
</select>
</mapper>
我们把表的字段名从新改下,以驼峰法命名
alter table 表名 change 旧字段名 新字段名 字段类型
我们的数据库名要与实体类名不一致的话就用as,强制一致
<?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:名称空间-->
<!--statement-->
<mapper namespace="com.taotao.mapper.BrandMapper">
<!--
数据库的字段名称 和 实体类的属性名称不一样,则不能自动封装数据
*起别名:对不一样的列名起别名,让别名和实体类的属性名一样
*缺点:每次查询都要定义一次别名
-->
<!-- sql片段 -->
<sql id="brand_column">
id, brandName as brand_name, companyName as company_name, ordered, description, status
</sql>
<select id="selectAll" resultType="brand">
select <include refid="brand_column"></include>
from tb_brand;
</select>
</mapper>
运行成功
resultMap的案例使用
<?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:名称空间-->
<!--statement-->
<mapper namespace="com.taotao.mapper.BrandMapper">
<!--
数据库的字段名称 和 实体类的属性名称不一样,则不能自动封装数据
*起别名:对不一样的列名起别名,让别名和实体类的属性名一样
*缺点:每次查询都要定义一次别名
*sql片段
*缺点:不灵活
*resultMap
1.定义<resultMap>标签
2.在<select>使用resultMap属性替换 resultType属性
-->
<resultMap id="brandResultMap" type="brand">
<result column="brandName" property="brand_name"></result>
<result column="companyName" property="company_name"></result>
</resultMap>
<!--
id:完成主键字段的映射
column:表的列名
property:实体类的属性名
result:完成一般字段的映射
column:表的列名
property:实体类的属性名
-->
<select id="selectAll" resultMap="brandResultMap">
select
*
from tb_brand;
</select>
</mapper>
查看详情
- 编写接口方法:Mapper接口
- 参数:id
- 结果:Brand
- 编写SQL语句:SQL映射文件
- 执行方法,测试
编写接口方法
package com.taotao.mapper;
import com.taotao.pojo.Brand;
import java.util.List;
@SuppressWarnings({"all"})
public interface BrandMapper {
/**
* * 查询所有
*/
public List<Brand> selectAll();
/**
* 查看详情,根据id查询
*
*/
Brand selectById(int id);
}
编写BrandMapper.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:名称空间-->
<!--statement-->
<mapper namespace="com.taotao.mapper.BrandMapper">
<!--
数据库的字段名称 和 实体类的属性名称不一样,则不能自动封装数据
*起别名:对不一样的列名起别名,让别名和实体类的属性名一样
*缺点:每次查询都要定义一次别名
*sql片段
*缺点:不灵活
*resultMap
1.定义<resultMap>标签
2.在<select>使用resultMap属性替换 resultType属性
-->
<resultMap id="brandResultMap" type="brand">
<result column="brandName" property="brand_name"></result>
<result column="companyName" property="company_name"></result>
</resultMap>
<!--
id:完成主键字段的映射
column:表的列名
property:实体类的属性名
result:完成一般字段的映射
column:表的列名
property:实体类的属性名
-->
<select id="selectAll" resultMap="brandResultMap">
select
*
from tb_brand;
</select>
<select id="selectById" resultMap="brandResultMap">
select *
from tb_brand where id = #{id};
</select>
</mapper>
编写测试方法MyBatisTest.java
public void testSelectById() throws IOException {
//接收参数
int id = 1;
//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.执行方法
Brand brand = brandMapper.selectById(id);
System.out.println(brand);
//5.释放资源
sqlSession.close();
}
运行测试
sql参数占位符
*参数占位符:
1.#{}:会将其替换为?,为了防止SQL注入
2.KaTeX parse error: Expected ‘EOF’, got ‘#’ at position 36: ….使用时机 *参数传递的时候:#{} *表名或者列名不固定的…{} 会存在SQL注入问题
sql特殊字符处理
*特殊字符处理:
比如小于号 < 就不能使用,因为是xml文件,所以编译器认为 < 是括号<>
1.转义字符 (比如 < 号的转义字符为 <)
2.COATA区 (输入CD)
<select id="selectById" resultMap="brandResultMap">
select *
from tb_brand where id <![CDATA[
<
]]> #{id};
parameterType
用于设置参数类型,该参数可以省略
条件查询
这篇我们只演示“散装参数”的方式
- 编写接口方法:Mapper接口
参数:所有查询条件
结果:List< Brand >
- 编写SQL语句:SQL映射文件
- 执行方法,测试
编写sql语句
编写BrandMapper.xml
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
where status = #{status} and
companyName like #{company_name} and
brandName like #{brand_name}
</select>
编写接口方法
编写BrandMapper.java
/**
* 条件查询
* *参数接收
* 1.散装参数:如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")
* 2.对象参数
* 3.map集合参数
* @param status
* @param company_name
* @param brand_name
* @return
*/
List<Brand> selectByCondition(@Param("status") int status,@Param("company_name") String company_name,@Param("brand_name") String brand_name);
//这里是第二种方法,不再演示
List<Brand> selectByCondition(Brand brand);
//这里是第三种方法,不再演示
List<Brand> selectByCondition(Map map);
编写测试方法
编写MyBatisTest.java
@Test
public void testSelectByCondtion() throws IOException {
//接收参数
int status = 1;
String company_name = "华为";
String brand_name = "华为";
//处理参数
company_name = company_name + "%";
brand_name = brand_name + "%";
//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.执行方法
List<Brand> brands = brandMapper.selectByCondition(status, company_name, brand_name);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
查询结果
多条件-动态条件查询
- MyBatis 对动态SQL有很强大的支撑
if
choose(when,otherwise)
trim(where,set)
foreach
- 目的是因为一个条件或多个条件
改造SQL语句
<!-- 动态条件查询-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
where
<if test="status != null">
status = #{status}
</if>
<if test="company_name != null and company_name != '' ">
and companyName like #{company_name}
</if>
<if test="brand_name != null and brand_name != '' ">
and brandName like #{brand_name}
</if>
</select>
恒等式语法1
<!-- 动态条件查询
*if:条件判断
*test:逻辑表达式
*问题:
*恒等式
-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
where
1 = 1
<if test="status != null">
and status = #{status}
</if>
<if test="company_name != null and company_name != '' ">
and companyName like #{company_name}
</if>
<if test="brand_name != null and brand_name != '' ">
and brandName like #{brand_name}
</if>
</select>
恒等式语法2(where标签)
<!-- 动态条件查询
*if:条件判断
*test:逻辑表达式
*问题:
*恒等式
-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="company_name != null and company_name != '' ">
and companyName like #{company_name}
</if>
<if test="brand_name != null and brand_name != '' ">
and brandName like #{brand_name}
</if>
</where>
</select>
单条件查询
编写接口方法
/**
* 单条件动态查询
* @param brand
* @return
*/
List<Brand> selectByConditionSingle(Brand brand);
生成statement
直接alt + enter
编写sql语句
编写BrandMapper.xml
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
where
<choose> <!--相当于switch-->
<when test="status !=null"> <!--相当于case-->
status = #{status}
</when>
<when test="company_name != null and company_name != ''"> <!--相当于case-->
and companyName like #{company_name}
</when>
<when test="brand_name != null and brand_name != ''"> <!--相当于case-->
and brandName like #{brand_name}
</when>
</choose>
</select>
编写测试方法
编写MyBatisTest.java
@Test
public void testSelectByCondtionSingle() throws IOException {
//接收参数
int status = 1;
String company_name = "华为";
String brand_name = "华为";
//处理参数
company_name = company_name + "%";
brand_name = brand_name + "%";
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompany_name(company_name);
brand.setBrand_name(brand_name);
//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.执行方法
List<Brand> brands = brandMapper.selectByConditionSingle(brand);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
查询结果
遇到问题
如果用户连一个条件也不传入,那么执行就会报错
解决方案
otherwise
编写sql语句1
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
where
<choose> <!--相当于switch-->
<when test="status !=null"> <!--相当于case-->
status = #{status}
</when>
<when test="company_name != null and company_name != ''"> <!--相当于case-->
and companyName like #{company_name}
</when>
<when test="brand_name != null and brand_name != ''"> <!--相当于case-->
and brandName like #{brand_name}
</when>
<otherwise>
1 = 1
</otherwise>
</choose>
</select>
编写sql语句2
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
<where>
<choose> <!--相当于switch-->
<when test="status !=null"> <!--相当于case-->
status = #{status}
</when>
<when test="company_name != null and company_name != ''"> <!--相当于case-->
and companyName like #{company_name}
</when>
<when test="brand_name != null and brand_name != ''"> <!--相当于case-->
and brandName like #{brand_name}
</when>
</choose>
</where>
</select>
查询结果
二.添加
- 编写接口方法:Mapper接口
参数:除了id之外的所有数据
结果:void
- 编写SQL语句:SQL映射文件
- 执行方法,测试
编写接口方法
编写BrandMapper.java
/**
* 添加
*/
void add(Brand brand);
编写sql语句
编写BrandMapper.xml
插件生成statement
<insert id="add">
insert into tb_brand(brandName, companyName, ordered, description, status)
values(#{brand_name}, #{company_name}, #{ordered}, #{description}, #{status});
</insert>
编写测试方法
编写MybatisTest.java
@Test
public void testAdd() throws IOException {
//接收参数
int status = 1;
String company_name = "波导手机";
String brand_name = "博导";
String description = "手机中的战斗机";
int ordered = 200;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompany_name(company_name);
brand.setBrand_name(brand_name);
brand.setDescription(description);
brand.setOrdered(ordered);
//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.执行方法
brandMapper.add(brand);
//5.提交事务
sqlSession.commit();
System.out.println("提交成功");
//6.释放资源
sqlSession.close();
}
是否自动提交事务
- MyBatis事务
openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit();手动提交事务
openSeesion(true):可以设置为自动提交事务(关闭事务)
添加 - 主键返回
- 在数据添加成功后,需要获取插入数据库数据的主键的值
比如:添加订单和订单项
-
添加订单
-
添加订单项,订单项中需要设置所属订单的id
更改sql语句
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand(brandName, companyName, ordered, description, status)
values(#{brand_name}, #{company_name}, #{ordered}, #{description}, #{status});
</insert>
编写测试方法
@Test
public void testAdd2() throws IOException {
//接收参数
int status = 1;
String company_name = "波导手机";
String brand_name = "博导";
String description = "手机中的战斗机";
int ordered = 200;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompany_name(company_name);
brand.setBrand_name(brand_name);
brand.setDescription(description);
brand.setOrdered(ordered);
//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.执行方法
brandMapper.add(brand);
Integer id = brand.getId();
System.out.println(id);
//5.提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
}
输出结果
三.修改
修改全部字段
编写接口方法
编写BrandMapper.java
/**
* 更新
*/
int update(Brand brand);
编写sql语句
编写BrandMapper.xml
<!--
修改
-->
<update id="update">
update tb_brand
set brandName = #{brand_name},
companyName = #{company_name},
ordered = #{ordered},
description = #{description},
status = #{status}
where id = #{id};
</update>
编写测试方法
编写MyBatisTest.java
@Test
public void testUpdate() throws IOException {
//接收参数
int status = 1;
String company_name = "波导手机";
String brand_name = "博导";
String description = "手机中的战斗机2";
int ordered = 400;
int id = 6; //修改id为6的数据
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompany_name(company_name);
brand.setBrand_name(brand_name);
brand.setDescription(description);
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();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
int count = brandMapper.update(brand); //返回受影响的行数
System.out.println(count);
//5.提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
}
查询结果
修改动态字段
编写sql语句
<update id="update">
update tb_brand
<set>
<if test="brand_name != null and brand_name != ''">
brandName = #{brand_name},
</if>
<if test="company_name != null and company_name != ''">
companyName = #{company_name},
</if>
<if test="ordered != null">
ordered = #{ordered},
</if>
<if test="description != null and description != ''">
description = #{description},
</if>
<if test="status != null">
status = #{status}
</if>
</set>
where id = #{id};
</update>
更改测试方法
编写MyBatisTest.java
把id = 6的数据的status字段改为 50
@Test
public void testUpdate() throws IOException {
//接收参数
int status = 50;
String company_name = "波导手机";
String brand_name = "博导";
String description = "手机中的战斗机2";
int ordered = 400;
int id = 6; //修改id为6的数据
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
// brand.setCompany_name(company_name);
// brand.setBrand_name(brand_name);
// brand.setDescription(description);
// 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();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
int count = brandMapper.update(brand); //返回受影响的行数
System.out.println(count);
//5.提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
}
修改结果
四.删除
删除一个
- 编写接口方法:Mapper接口
参数:id
结果:void
- 编写SQL语句:SQL映射文件
- 执行方法:测试
编写接口方法
/**
* 根据id删除
*/
void deleteById(int id);
编写sql语句
编写BrandMapper.xml
<!--
删除
-->
<delete id="deleteById">
delete from tb_brand where id = #{id};
</delete>
编写测试方法
编写MyBatisTest.java
@Test
public void testDeleteById() throws IOException {
//接收参数
int id = 8;
//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.执行方法
brandMapper.deleteById(id);
//5.提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
}
删除结果
批量删除
- 编写接口方法:Mapper接口
参数:id数组
结果:void
- 编写SQL语句:SQL映射文件
- 执行方法,测试
编写接口方法
编写BrandMapper.java
/**
* 批量删除
*/
void deleteByIds(@Param("ids") int[] ids); //@Param("ids")将map.key“id”变为ids
编写sql语句
编写BrandMapper.xml
<!--
mybatis会将数组参数,封装为一个Map集合,
*默认:array = 数组
*使用@Param注解改变map集合的默认key的名称
-->
<delete id="deleteByIds">
delete from tb_brand where id
in (
<foreach collection="ids" item="id" separator=","> # separator分隔符
#{id}
</foreach>
);
</delete>
编写测试方法
编写MyBatisTest.java
@Test
public void testDeleteByIds() throws IOException {
//接收参数
int []ids = {6,7};
//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.执行方法
brandMapper.deleteByIds(ids);
//5.提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
}
删除结果
标签:status,name,brand,改查,Mybatis,MyBatis,编写,company,id 来源: https://blog.csdn.net/m0_67393039/article/details/123626788