目录
前言
针对表格实现查询 、 按条件查询 、 添加 、 删除 、 批量删除 、 修改 等功能,而这些功能其实就是对数据库表中进行 CRUD操作。
一、搭建环境
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, '华为致力于把数字世界带入每个人、每个家庭、
('小米', '小米科技有限公司', 50, 'are you ok', 1);
2、 实体类 Brand
在 com.itheima.pojo 包下创建 Brand 实体类。
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
//省略 setter and getter。自己写时要补全这部分代码
}
setter and getter,to_String方法必须生成
3、引入配置文件
在resources下引入xml文件
并且com.ucloud.mapper一定要逐级建包,并引入mapper.xml文件
4、安装 MyBatisX 插件
MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
主要功能 :XML映射配置文件 和 接口方法 间相互跳转 ,根据接口方法生成 statement
二、命令
1.查询所有
1)Mapper接口
public interface BrandMapper {
public List<Brand> selectAll();
}
2)Mapper.xml
<mapper namespace="com.ucloud.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<!--进行别名定义-->
<select id="selectAll" resultType="brand" resultMap="brandResultMap">
select * from tb_brand;
</select>
</mapper>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testSelectAll() throws IOException {
//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. 执行sql
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = brandMapper.selectAll();
//参数是一个字符串,该字符串必须是映射配置文件的namespace.id
System.out.println(brands);
//4. 释放资源
sqlSession.close();
}
小结:
实体类属性名 和 数据库表列名 不一致,不能自动封装数据
==起别名:==在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样
可以定义 片段,提升复用性
==resultMap:==定义 完成不一致的属性名和列名的映射
2.查询详细
1)Mapper接口
Brand selectById(int id);
2)Mapper.xml
<select id="selectById" parameterType="int" resultMap="brandResultMap">
select * from tb_brand where id=#{id};
</select>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testSelectById() throws IOException {
//接收参数
int id=1;
//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. 执行sql
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
Brand brand = brandMapper.selectById(id);
//参数是一个字符串,该字符串必须是映射配置文件的namespace.id
System.out.println(brand);
//4. 释放资源
sqlSession.close();
}
4)mybatis提供了两种参数占位符:
#{} :执行SQL时,会将 #{} 占位符替换为?,将来自动设置参数值。从上述例子可 以看出使用#{} 底层使用的是PreparedStatement,好处:安全
${} :拼接SQL。底层使用的是 Statement ,会存在SQL注入问题。
5)parameterType使用
对于有参数的mapper接口方法,我们在映射配置文件中应该配置 ParameterType 来 指定参数类型。只不过该属性都可以省略。
6)特殊字符 " > "
第一种方法:
第二种方法:
3.多条件查询
1)Mapper接口
List<Brand>selectByCondition(
@Param("status")int status,
@Param("companyName")String companyName,
@Param("brandName")String brandName
);
2)Mapper.xml
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
<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>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testSelectByCondition() throws IOException {
//接收参数
int status=1;
String companyName="华为";
String brandName="华为";
companyName="%"+companyName+"%";
brandName="%"+brandName+"%";
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.
getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
List<Brand> brands= brandMapper.selectByCondition(status,companyName,brandName);
System.out.println(brands);
sqlSession.close();
}
4)@Param("参数名称")
使用 @Param("参数名称") 标记每一个参数,在映射配置文件中就需要使用 #{参数 名称} 进行占位
5)if标签
针对上述的需要,Mybatis对动态SQL有很强大的支撑:
if
choose (when, otherwise)
trim (where, set)
foreach
if 标签:条件判断
test 属性:逻辑表达式
6)where 标签
作用: 替换where关键字
会动态的去掉第一个条件前的 and
如果所有的参数没有值则不加where关键字
4.单个条件动态查询
1)Mapper接口
List<Brand>selectByConditionSingle(Brand brand);
2)Mapper.xml
<select id="selectByConditionSingle" resultMap="brandResultMap">
select * from tb_brand
<where>
<choose>
<when test="status!=null"><!--相当于case-->
status=#{status}
</when>
<when test="companyName!=null and companyName!=''"><!--相当于case-->
company_name like #{companyName}
</when>
<when test="brandName!=null and brandName!=''"><!--相当于case-->
brand_name like #{brandName}
</when>
</choose>
</where>
</select>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testSelectBySingle() throws IOException {
//接收参数
int status=1;
String companyName="华为";
String brandName="华为";
companyName="%"+companyName+"%";
brandName="%"+brandName+"%";
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.
getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
List<Brand> brands= brandMapper.selectByCondition(status,companyName,brandName);
System.out.println(brands);
sqlSession.close();
}
5.增加
1)Mapper接口
void add(Brand brand);
2)Mapper.xml
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand (brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testAdd()throws IOException{
//接收参数
int status=1;
String companyName="苹果手机";
String brandName="苹果";
String description="手机中贵族";
int ordered=100;
//封装对象
Brand brand=new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
String url="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(url);
//1.加载mybatis核心配置文件mybatis-config.xml 获取SqlSessionFactory
SqlSessionFactory factory=
new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession= factory.openSession();
//3.执行方法 获取Mapper接口的代理对象
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
brandMapper.add(brand);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
}
6.修改
1)Mapper接口
void update (Brand brand);
2)Mapper.xml
<update id="update">
update tb_brand
<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>
</set>
where id = #{id};
</update>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testUpdate()throws IOException{
//接收参数
int status=1;
String companyName="苹果手机";
String brandName="苹果";
String description="手机中贵族";
int ordered=100;
int id=1;
//封装对象
Brand brand=new Brand();
brand.setStatus(status);
brand.setId(id);
String url="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(url);
//1.加载mybatis核心配置文件mybatis-config.xml 获取SqlSessionFactory
SqlSessionFactory factory=
new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession= factory.openSession();
//3.执行方法 获取Mapper接口的代理对象
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
brandMapper.update(brand);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
}
7.删除(通过id)
1)Mapper接口
void deleteById(int id);
2)Mapper.xml
<delete id="deleteById">
delete from tb_brand where id=#{id};
</delete>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testDelete()throws IOException{
int id=2;
String url="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(url);
//1.加载mybatis核心配置文件mybatis-config.xml 获取SqlSessionFactory
SqlSessionFactory factory=
new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession= factory.openSession();
//3.执行方法 获取Mapper接口的代理对象
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
brandMapper.deleteById(id);
sqlSession.commit();
sqlSession.close();
}
8. 批量删除
1)Mapper接口
void deleteByIds(int[] ids);
2)Mapper.xml
<!--separator分隔符-->
<delete id="deleteByIds">
delete from tb_brand where id in
<foreach collection="array" item="id" separator=","
open="(" close=")">
#{id}
</foreach>
</delete>
3)编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testDeleteByIds()throws IOException{
int[] ids={1,3};
String url="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(url);
//1.加载mybatis核心配置文件mybatis-config.xml 获取SqlSessionFactory
SqlSessionFactory factory=
new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession= factory.openSession();
//3.执行方法 获取Mapper接口的代理对象
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
brandMapper.deleteByIds(ids);
sqlSession.commit();
sqlSession.close();
}
4)标签性能
在 BrandMapper.xml 映射配置文件中编写删除多条数据的 statement 。 编写SQL时需要遍历数组来拼接SQL语句。Mybatis 提供了 foreach 标签供我们使用
foreach 标签
用来迭代任何可迭代的对象(如数组,集合)。
collection 属性:
mybatis会将数组参数,封装为一个Map集合。
----》 默认:array = 数组
-----》使用@Param注解改变map集合的默认key的名称
item 属性:
本次迭代获取到的元素。
separator 属性:
集合项迭代之间的分隔符。
foreach 标签不会错误地添加多余的 分隔符。也就是最后一次迭代不会加分隔符。
open 属性:
该属性值是在拼接SQL语句之前拼接的语句,只会拼接一次
close 属性:
该属性值是在拼接SQL语句拼接后拼接的语句,只会拼接一次