环境准备
1.数据库表tb_brand
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand(-- id 主键id int primary key auto_increment,-- 品牌名称brand_name varchar(20),-- 企业名称company_name varchar(20),-- 排序字段ordered int,-- 描述信息description varchar(100),-- 状态:0:禁用 1:启用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;
2.实体类Brand
public class Brand {/*** id int primary key auto_increment,* brand_name varchar(20),* company_name varchar(20),* ordered int,* description varchar(100),* status int*///id 主键private Integer id;//品牌名称private String brand_name;//企业名称private String company_name;//排序字段private Integer ordered;//描述信息private String description;//状态:0:禁用 1:启用private Integer status;public Brand() {}public Brand(Integer id, String brand_name, String company_name, Integer ordered, String description, Integer status) {this.id = id;this.brand_name = brand_name;this.company_name = company_name;this.ordered = ordered;this.description = description;this.status = status;}/*** 获取* @return id*/public Integer getId() {return id;}/*** 设置* @param id*/public void setId(Integer id) {this.id = id;}/*** 获取* @return brand_name*/public String getBrand_name() {return brand_name;}/*** 设置* @param brand_name*/public void setBrand_name(String brand_name) {this.brand_name = brand_name;}/*** 获取* @return company_name*/public String getCompany_name() {return company_name;}/*** 设置* @param company_name*/public void setCompany_name(String company_name) {this.company_name = company_name;}/*** 获取* @return ordered*/public Integer getOrdered() {return ordered;}/*** 设置* @param ordered*/public void setOrdered(Integer ordered) {this.ordered = ordered;}/*** 获取* @return description*/public String getDescription() {return description;}/*** 设置* @param description*/public void setDescription(String description) {this.description = description;}/*** 获取* @return status*/public Integer getStatus() {return status;}/*** 设置* @param status*/public void setStatus(Integer status) {this.status = status;}public String toString() {return "Brand{id = " + id + ", brand_name = " + brand_name + ", company_name = " + company_name + ", ordered = " + ordered + ", description = " + description + ", status = " + status + "}";}
}
3.测试用例
在test/java目录下新建测试用例MybatisTest
4.安装MyBatisX插件
和安装maven helper插件一样,如果在plugins里搜不到,可以去官网进行下载自己idea对应的版本
MyBatisX官网
看清楚自己idea的版本再进行下载,否则不可用,下载完的压缩包记得解压再查找对应的jar包进行加载,但我下载解压完之后再去plugins里搜索就搜到了,如果下载完还搜不到的可以点击plugins页面右边的设置进行手动导入
安装这个插件之后从映射文件转到mapper接口就好找多了,点击xml文件页面左侧的小蓝鸟就会去到对应的mapper接口的方法,再点击mapper接口方法左侧的小红鸟就能去到相对应的sql映射语句,超级方便哒
配置文件完成增删改查
编写数据库
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand(-- id 主键id int primary key auto_increment,-- 品牌名称brand_name varchar(20),-- 企业名称company_name varchar(20),-- 排序字段ordered int,-- 描述信息description varchar(100),-- 状态:0:禁用 1:启用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类
package com.svt.pojo;public class Brand {/*** id int primary key auto_increment,* brand_name varchar(20),* company_name varchar(20),* ordered int,* description varchar(100),* status int*///id 主键private Integer id;//品牌名称private String brand_name;//企业名称private String company_name;//排序字段private Integer ordered;//描述信息private String description;//状态:0:禁用 1:启用private Integer status;public Brand() {}public Brand(Integer id, String brand_name, String company_name, Integer ordered, String description, Integer status) {this.id = id;this.brand_name = brand_name;this.company_name = company_name;this.ordered = ordered;this.description = description;this.status = status;}/*** 获取* @return id*/public Integer getId() {return id;}/*** 设置* @param id*/public void setId(Integer id) {this.id = id;}/*** 获取* @return brand_name*/public String getBrand_name() {return brand_name;}/*** 设置* @param brand_name*/public void setBrand_name(String brand_name) {this.brand_name = brand_name;}/*** 获取* @return company_name*/public String getCompany_name() {return company_name;}/*** 设置* @param company_name*/public void setCompany_name(String company_name) {this.company_name = company_name;}/*** 获取* @return ordered*/public Integer getOrdered() {return ordered;}/*** 设置* @param ordered*/public void setOrdered(Integer ordered) {this.ordered = ordered;}/*** 获取* @return description*/public String getDescription() {return description;}/*** 设置* @param description*/public void setDescription(String description) {this.description = description;}/*** 获取* @return status*/public Integer getStatus() {return status;}/*** 设置* @param status*/public void setStatus(Integer status) {this.status = status;}public String toString() {return "Brand{id = " + id + ", brand_name = " + brand_name + ", company_name = " + company_name + ", ordered = " + ordered + ", description = " + description + ", status = " + status + "}";}
}
查询
①查询所有数据
1.定义Mapper接口
public interface BrandMapper {/*** 查询所有*/List<Brand> selectAll();
}
2.配置xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--mapper:根标签namespace:命名空间-->
<mapper namespace="com.svt.mapper.BrandMapper">
<!--定义查询语句--><select id="selectAll" resultType="brand">select * from tb_brand;</select>
</mapper>
3.在test文件夹下编写测试用例
@Testpublic void testSelectAll() throws IOException {//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句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();}
4.数据显示和数据库内一致则表示查询成功
解决:实体类属性名和数据库表列名不一致,不能自动封装数据
- 起别名:对不一样的列名起别名,让别名和实体类的属性名一样
- 缺点:每次查询都要定义一次别名
- sql片段
- 缺点:不灵活
- sql片段
- 缺点:每次查询都要定义一次别名
- resultMap:
- 1.定义标签
- 2.在标签中,使用resultMap属性替换resultType属性
这里以resultMap为详细讲解
比如你数据库内列名是brand_name,写实体类的时候写成了brandName,又不想更改,那么就可以用下面这种方式用resultMap映射
<!--id:唯一标识result:映射的类型,支持别名--><resultMap id="brandResultMap" type="brand"><!--id:完成主键字段的映射column:表的列名property:实体类的属性名result:完成一般字段的映射column:表的列名property:实体类的属性名--><result column="brand_name" property="brandName"/><result column="company_name" property="companyName"/><!--前面写数据库内名称 后面写自定义类中名称 如果两者名字不一样自动封装不了可以用--></resultMap><select id="selectAll" resultMap="brandResultMap">select * from tb_brand;</select>
②查看详情
1.定义Mapper接口
public interface UserMapper {List<User> selectAll();User selectById(int id);
}
2.配置xml
-
参数占位符
- 1.#{}:会将其替换为?,为了防止sql注入
- 2.${}:会将其替换为1,拼sql,会存在sql注入的问题
- 3.使用时机
- 参数传递的时候:#{}
- 表名或者列名不固定的情况下:${} 会存在sql注入的问题
-
参数类型:parameterType设置参数类型:可以省略
- 特殊字符处理:
- 1.转义字符:比如<就写
<
- 2.CDATA区:CD+回车
<![CDATA[ 内容 ]]>
- 1.转义字符:比如<就写
- 特殊字符处理:
<select id="selectById" resultType="brand">select *from tb_brandwhere id=#{id};</select>
3.在test文件夹下编写测试用例
@Testpublic void testSelectById() throws IOException {//接收参数int id=1;//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句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();}
4.数据显示和数据库内一致则表示查询成功
③多条件查询
散装参数:如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)
1.定义Mapper接口
List<Brand> selectByCondition(@Param("status") int status,@Param("company_name") String company_name,@Param("brand_name") String brand_name);
}
2.配置xml
<!--条件查询--><select id="selectByCondition" resultType="brand">select * from tb_brandwhere status = #{status}and company_name like #{company_name}and brand_name like #{brand_name};</select>
3.在test文件夹下编写测试用例
@Testpublic void testSelectByCondition() throws IOException {//接收参数int status=1;String company_name="华为";String brand_name="华为";//处理参数company_name="%"+company_name+"%";brand_name="%"+brand_name+"%";//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句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();}
4.数据符合条件查询则表示查询成功
对象参数:对象的属性名称要和参数占位符名称一致
1.定义Mapper接口
List<Brand> selectByCondition(Brand brand);
2.配置xml
不需要更改,沿用散装参数的即可
3.在test文件夹下编写测试用例
添加一个封装对象
@Testpublic void testSelectByCondition() 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//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法List<Brand> brands = brandMapper.selectByCondition(brand);System.out.println(brands);//5.释放资源sqlSession.close();}
4.数据符合条件查询则表示查询成功
map集合参数
1.定义Mapper接口
List<Brand> selectByCondition(Map map);
2.配置xml
不需要更改,沿用散装参数的即可
3.在test文件夹下编写测试用例
将封装对象改为Map集合存放
@Testpublic void testSelectByCondition() throws IOException {//接收参数int status=1;String company_name="华为";String brand_name="华为";//处理参数company_name="%"+company_name+"%";brand_name="%"+brand_name+"%";Map map=new HashMap();map.put("status",status);map.put("company_name",company_name);map.put("brand_name",brand_name);//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法List<Brand> brands = brandMapper.selectByCondition(map);System.out.println(brands);//5.释放资源sqlSession.close();}
4.数据符合条件查询则表示查询成功
④多条件动态查询
SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL
用户输入查询的条件不一样,我们的sql语句也不一样,这时候我们修改一下xml文件内的sql语句即可
<!--动态条件查询--><select id="selectByCondition" resultType="brand">select * from tb_brandwhere<if test="status != null">status = #{status}</if><if test="company_name != null and company_name != '' ">and company_name like #{company_name}</if><if test="brand_name != null and brand_name != '' ">and brand_name like #{brand_name};</if></select>
修改过后再来注释掉一个查询条件进行尝试,成功则代表语句正确,失败了再逐字逐码查看一下
但是这样写会有一个问题,如果第一个条件不存在,直接查找第二个条件,第二个条件内有and开头,会造成语法错误,然后查询就会出错,我们可以用以下几种方式再继续完善上面的代码
1.恒等式:在where后面加一个恒等式,再在if判断内所有语句前加上and,这样就能执行成功,比如where 1=1 and…,语法就不会出错
<select id="selectByCondition" resultType="brand">select * from tb_brandwhere 1=1<if test="status != null">and status = #{status}</if><if test="company_name != null and company_name != '' ">and company_name like #{company_name}</if><if test="brand_name != null and brand_name != '' ">and brand_name like #{brand_name};</if></select>
这时候仅查询公司名称也不会出错啦
2.标签替换where关键字
mybatis自带的标签也能解决这个问题
<select id="selectByCondition" resultType="brand">select * from tb_brand/*where 1=1*/<where><if test="status != null">and status = #{status}</if><if test="company_name != null and company_name != '' ">and company_name like #{company_name}</if><if test="brand_name != null and brand_name != '' ">and brand_name like #{brand_name};</if></where></select>
呈现结果如下图
⑤单条件的动态查询
从多个条件中选择一个条件进行查询
就是一个下拉框,在里面有多个选项,用户只能选择一个进行查询
1.定义Mapper接口
List<Brand> selectByConditionSingle(Brand brand);
2.配置xml文件
如果写的时候choose会报错记得别写/* */
这样的注释方式,要写<!-- -->
这样的,会被当成sql语句一起进行编译的
- sql语句一
<!--单条件动态查询--><select id="selectByConditionSingle" resultType="brand">select * from tb_brandwhere<!-- 相当于switch --><choose><when test="status != null"><!-- 相当于case的查询条件-->status = #{status}</when><when test="company_name != null and company_name != ''"><!--相当于case的查询条件 -->company_name like #{company_name}</when><when test="brand_name != null and brand_name != '' "><!--相当于case的查询条件 -->brand_name like #{brand_name};</when><otherwise>1=1</otherwise></choose></select>
- sql语句二
<select id="selectByConditionSingle" resultType="brand">select * from tb_brand<where><!-- 相当于switch--><choose><when test="status != null"><!-- 相当于case的查询条件-->status = #{status}</when><when test="company_name != null and company_name != ''"><!--相当于case的查询条件 -->company_name like #{company_name}</when><when test="brand_name != null and brand_name != '' "><!--相当于case的查询条件 -->brand_name like #{brand_name};</when></choose></where></select>
3.在test文件夹下编写测试用例
@Testpublic void testSelectByConditionSingle() 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//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句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();}
添加
①添加数据
1.定义Mapper接口
/*** 添加*/void add(Brand brand);
2.配置xml文件
<!--添加--><insert id="add">insert into tb_brand (brand_name,company_name,ordered,description,status)values (#{brand_name},#{company_name},#{ordered},#{description},#{status});</insert>
3.在test文件夹下编写测试用例
这里要注意,jdbc的事务提交默认是false,所以说是需要我们自己手动提交事务的,有两种选择,一是默认开启事务,二是在最后手动提交事务,如果不这样做的话idea显示运行成功但是数据库里是没有数据的,因为没有提交事务,数据回滚了
@Testpublic void testAdd() throws IOException {//接收参数int status=1;String company_name="菠萝手机";String brand_name="菠萝";String description="手机中的战斗机";int ordered=100;//封装对象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//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.add(brand);//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
②主键返回
在数据添加成功后,需要获取插入数据库数据的主键的值
只有两个属性需要添加,useGeneratedKeys和keyProperty,添加上两个属性就能获得添加的主键了
1.配置xml文件
<insert id="add" useGeneratedKeys="true" keyProperty="id">insert into tb_brand (brand_name,company_name,ordered,description,status)values (#{brand_name},#{company_name},#{ordered},#{description},#{status});</insert>
2.在test文件夹下编写测试用例
@Testpublic void testAdd() throws IOException {//接收参数int status=1;String company_name="菠萝手机";String brand_name="菠萝";String description="手机中的战斗机";int ordered=100;//封装对象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//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.add(brand);Integer id = brand.getId();System.out.println(id);//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
修改
①修改全部字段
1.定义Mapper接口
/*** 修改*/int update(Brand brand);
2.配置xml文件
<!--修改--><update id="update">update tb_brandsetbrand_name=#{brand_name},company_name=#{company_name},ordered=#{ordered},description=#{description},status=#{status}where id=#{id};</update>
3.在test文件夹下编写测试用例
@Testpublic void testUpdate() throws IOException {//接收参数int status=1;String company_name="菠萝手机";String brand_name="菠萝";String description="菠萝手机,手机中的战斗机";int ordered=200;int id=5;//封装对象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//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法int count = brandMapper.update(brand);System.out.println(count);//影响的行数//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
影响了一行数据
②修改动态字段
1.配置xml文件
<update id="update">update tb_brand<set><if test="brand_name != null and brand_name != ''">brand_name=#{brand_name},</if><if test="company_name != null and company_name != ''">company_name=#{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>
2.在test文件夹下编写测试用例
@Testpublic void testUpdate() throws IOException {//接收参数int status=0;String company_name="菠萝手机";String brand_name="菠萝";String description="菠萝手机,手机中的战斗机";int ordered=200;int id=5;//封装对象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//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法int count = brandMapper.update(brand);System.out.println(count);//影响的行数//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
可以看到数据库内的数据确实是只改变了status,说明我们的修改动态字段编写成功
删除
删除一个
删除一行数据
1.定义Mapper接口
/*** 根据id删除*/void deleteById(int id);
2.配置xml文件
<!--根据id修改--><delete id="deleteById">delete from tb_brand where id = #{id};</delete>
3.在test文件夹下编写测试用例
@Testpublic void testDeleteById() throws IOException {//接收参数int id=6;//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.deleteById(id);//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
运行成功,id为6的数据已经被删除
批量删除
1.定义Mapper接口
/*** 根据id批量删除*/void deleteByIds(@Param("ids") int[] ids);
2.配置xml文件
mybatis会将数组参数,封装为一个Map集合,默认名是array,但我们可以使用@Param注解改变map集合的默认key的名称,这里我就用了注解
<!--根据id批量删除--><!--mybatis会将数组参数,封装为一个Map集合默认:array=数组使用@Param注解改变map集合的默认key的名称separator:分隔符--><delete id="deleteByIds">delete from tb_brand where idin<foreach collection="ids" item="id" separator="," open="(" close=")">#{id}</foreach>;</delete>
如果不用注解,就要在collection集合名内写array
3.在test文件夹下编写测试用例
@Testpublic void testDeleteByIds() throws IOException {//接收参数int[] ids={5,8,9};//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.deleteByIds(ids);//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
成功删除了5,8,9号数据
注解完成增删改查
使用注解开发会比配置文件开发更加方便
注解完成简单功能
配置文件完成复杂功能
查询@Select
1.定义Mapper接口
public interface UserMapper {List<User> selectAll();@Select("select * from tb_user where id=#{id}")User selectById(int id);
}
2.在test文件夹下编写测试用例
@Testpublic void testSelectById() throws IOException {//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//4.执行方法User user = userMapper.selectById(1);System.out.println(user);//5.释放资源sqlSession.close();}
查询出来的数据与数据库内数据1号一致,查询成功
添加@Insert
1.定义Mapper接口
@Insert("insert into tb_user (username,password,gender,addr) values (#{username},#{password},#{gender},#{addr});")void add(User user);
2.在test文件夹下编写测试用例
@Testpublic void testAdd1() throws IOException {//接收参数String username="赵六";String password="666";String gender="男";String addr="江苏";//封装对象User user = new User();user.setUsername(username);user.setPassword(password);user.setGender(gender);user.setAddr(addr);//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//4.执行方法userMapper.add(user);//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
修改@Update
1.定义Mapper接口
@Update("update tb_user " +"set username=#{username},password=#{password},gender=#{gender},addr=#{addr}" +" where id=#{id}")int update(User user);
2.在test文件夹下编写测试用例
@Testpublic void testUpdate1() throws IOException {//接收参数String username="赵六";String password="6666";String gender="男";String addr="江苏";Integer id=4;//封装对象User user = new User();user.setUsername(username);user.setPassword(password);user.setGender(gender);user.setAddr(addr);user.setId(id);//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//4.执行方法int count = userMapper.update(user);System.out.println(count);//影响的行数//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
赵六的密码已从666变为了6666,修改成功
删除@Delete
1.定义Mapper接口
@Delete("delete from tb_user where id = #{id}")void deleteById(int id);
2.在test文件夹下编写测试用例
@Testpublic void testDelete() throws IOException {//接收参数int id=4;//1.获取SqlSessionFactory//1.加载mybatis核心配置文件,获取 SqlSessionFactory 对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取 SqlSession 对象,用它执行 SQL 语句SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//4.执行方法userMapper.deleteById(id);//提交事务sqlSession.commit();//5.释放资源sqlSession.close();}
已成功删除id为4的数据
以上就是注解开发的简单增删改查