目录
Mybatis 针对 CURD 操作都提供了对应的注解,已经做到见名知意。如下:
查询 :@Select
添加 :@Insert
修改 :@Update
删除 :@Delete
接下来我们做一个案例来使用 Mybatis 的注解开发
针对上述的需要,Mybatis对动态SQL有很强大的支撑:
if
choose (when, otherwise)
trim (where, set)
foreach
如上图所示,在查询时只能选择 品牌名称、当前状态、企业名称 这三个条件中的一个,但是用户到底选择哪儿一个,我们并不能确定。这种就属于单个条件的动态SQL语句。
这种需求需要使用到 choose(when,otherwise)标签 实现, 而 choose 标签类似于Java 中的switch语句。
通过一个案例来使用这些标签
- -- 删除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',
在 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。自己写时要补全这部分代码
- }
测试代码需要在 test/java 目录下创建包及测试用例。项目结构如下:

- package com.itheima.test;
-
- public class MybatisTest {
- }
MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
主要功能
XML映射配置文件 和 接口方法 间相互跳转
根据接口方法生成 statement
安装方式

重启一下

红色头绳的表示映射配置文件,蓝色头绳的表示mapper接口。在mapper接口点击红色头绳的小鸟图标会自动跳转到对应的映射配置文件,在映射配置文件中点击蓝色头绳的小鸟图标会自动跳转到对应的mapper接口。也可以在mapper接口中定义方法,自动生成映射配置文件中的 statement
编写接口方法:Mapper接口
参数:无
查询所有数据功能是不需要根据任何条件进行查询的,所以此方法不需要参数。
结果:List
我们会将查询出来的每一条数据封装成一个
Brand对象,而多条数据封装多个Brand对象,需要将这些对象封装到List集合中返回。执行方法、测试
BrandMapper.java接口在 com.itheima.mapper 包写创建名为 BrandMapper 的接口。并在该接口中定义 List 方法。
- package com.itheima.mapper;
-
- import com.itheima.pojo.Brand;
- import org.apache.ibatis.annotations.Param;
- import org.apache.ibatis.annotations.Select;
-
- import java.util.List;
- import java.util.Map;
-
- public interface BrandMapper {
- //查询所有的方法
- @Select("select * from tb_brand")
- public List
selectAll(); - //按照id查找信息
- Brand selectById(int id);
-
- //有条件查询三种方法
- List
selectByCondition(@Param("status") int status, - @Param("companyName") String companyName,
- @Param("brandName") String brandName);
-
- // List
selectByCondition(Brand brand); -
- List
selectByCondition(Map map); - //单条件查询
- List
selectByConditionSingle(Brand brand); - //添加功能·
- void add(Brand brand);
- //动态修改
- int update(Brand brand);
- //删除一条记录
- void deleteById(int id);
- //批量删除
- void deleteByIds(@Param("ids")int[] ids);
- }
编写测试方法MybatisTest 类- package com.itheima.test;
-
- import com.itheima.mapper.BrandMapper;
- import com.itheima.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.HashMap;
- import java.util.List;
- import java.util.Map;
-
- public class MybatisTest {
- //1.查询所有
- @Test
- public void testSelecctAll() throws IOException {
- 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
brands = brandMapper.selectAll(); - System.out.println(brands);
- sqlSession.close();
- }
-
- //2.查询详细
-
- @Test
- public void testSelecctByIdl() throws IOException {
- int id = 1;
- 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);
- //改变sql语句
- Brand brand = brandMapper.selectById(id);
- System.out.println(brand);
- sqlSession.close();
- }
-
- //3.多条件查询
- @Test
- public void testselectByCondition() throws IOException {
- int status = 1;
- String companyName = "华为";
- String brandName = "华为";
- //数据处理
- companyName = "%" + companyName + "%";
- brandName = "%" + brandName + "%";
-
- /* Brand brand = new Brand();
- brand.setStatus(status);
- brand.setCompanyName(companyName);
- brand.setBrandName(brandName);*/
-
- //List
brands = brandMapper.selectByCondition(brand); - 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);
- //方式三 :接口方法参数是 map集合对象 方式调用的方法
- Map map = new HashMap();
- // map.put("status" , status);
- map.put("companyName", companyName);
- // map.put("brandName" , brandName);
- //改变sql语句
- List
brands = brandMapper.selectByCondition(map); - System.out.println(brands);
-
-
- // List
brands = brandMapper.selectByCondition(status, companyName, brandName); - System.out.println(brands);
- sqlSession.close();
- }
-
- //4.单条件查询
- @Test
- public void testselectByConditionSingle() throws IOException {
- int status = 1;
- String companyName = "华为";
- String brandName = "华为";
- //数据处理
- companyName = "%" + companyName + "%";
- brandName = "%" + brandName + "%";
-
- Brand brand = new Brand();
- brand.setStatus(status);
- // brand.setCompanyName(companyName);
- // brand.setBrandName(brandName);
-
- //List
brands = brandMapper.selectByCondition(brand); - 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);
-
- //改变sql语句
- List
brands = brandMapper.selectByConditionSingle(brand); - System.out.println(brands);
- sqlSession.close();
- }
- //5.普通添加功能
-
- @Test
- public void testadd() throws IOException {
- int status = 1;
- String companyName = "刘德华品牌手机";
- String brandName = "红米";
- String description = "号的中国制造";
- int order = 100;
- //数据处理
- // companyName="%"+companyName+"%";
- // brandName="%"+brandName+"%";
-
- Brand brand = new Brand();
- brand.setStatus(status);
- brand.setCompanyName(companyName);
- brand.setBrandName(brandName);
- brand.setDescription(description);
- brand.setOrdered(order);
-
- //List
brands = brandMapper.selectByCondition(brand); - String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
- BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
-
- //改变sql语句
- brandMapper.add(brand);
- Integer id = brand.getId();
- System.out.println(id);
- //提交事务
- // sqlSession.commit();
- //关闭资源
-
- sqlSession.close();
- }
- //6.动态修改功能
- @Test
- public void testupdate() throws IOException {
- int status = 1;
- String companyName = "kk";
- String brandName = "kk";
- String description = "号的中国制造";
- int order = 100;
- int id=5;
- //数据处理
- // companyName="%"+companyName+"%";
- // brandName="%"+brandName+"%";
-
- Brand brand = new Brand();
- brand.setStatus(status);
- brand.setCompanyName(companyName);
- brand.setBrandName(brandName);
- // brand.setDescription(description);
- // brand.setOrdered(order);
- brand.setId(id);
-
- //List
brands = brandMapper.selectByCondition(brand); - String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
- BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
-
- //改变sql语句
- int count = brandMapper.update(brand);
- System.out.println(count);
- //提交事务
- // sqlSession.commit();
- //关闭资源
-
- sqlSession.close();
- }
- //删除一条记录
- @Test
- public void testdeleteById() throws IOException {
-
- int id=5;
- //数据处理
- // companyName="%"+companyName+"%";
- // brandName="%"+brandName+"%";
-
-
-
- //List
brands = brandMapper.selectByCondition(brand); - String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
- BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
-
- //改变sql语句
- brandMapper.deleteById(id);
- //提交事务
- // sqlSession.commit();
- //关闭资源
-
- sqlSession.close();
- }
- //批量删除
- @Test
- public void testdeleteByIds() throws IOException {
-
- int[] ids={6,7,8};
- //数据处理
- // companyName="%"+companyName+"%";
- // brandName="%"+brandName+"%";
-
-
-
- //List
brands = brandMapper.selectByCondition(brand); - String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
- BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
-
- //改变sql语句
- brandMapper.deleteByIds(ids);
- //提交事务
- // sqlSession.commit();
- //关闭资源
-
- sqlSession.close();
- }
- }
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.itheima.mapper.BrandMapper">
-
-
- <resultMap id="brandresultMapper" type="brand">
-
- <result column="brand_Name" property="brandName"/>
- <result column="company_Name" property="companyName"/>
- resultMap>
-
-
- <select id="selectAll" resultMap="brandresultMapper">
- select * from tb_brand;
-
- select>
-
-
-
-
- <select id="selectById" resultMap="brandresultMapper">
- select *
- from tb_brand
- where id = #{id};
- select>
-
-
- <select id="selectByCondition" resultMap="brandresultMapper">
- select *
- from tb_brand
-
- <where>
- <if test="status!=null">
- and status = #{status}
-
- if>
- <if test="company_name!=null and company_name !='' ">
- and company_name like #{companyName}
-
- if>
- <if test="brandName!=null and brandName!='' ">
- and brand_name like #{brandName}
- if>
-
- where>
-
-
- select>
-
- <select id="selectByConditionSingle" resultMap="brandresultMapper">
- select *
- from tb_brand
- <where>
- <choose>
- <when test="status != null">
- status = #{status}
- when>
- <when test="companyName != null and companyName != '' ">
- company_name like #{companyName}
- when>
- <when test="brandName != null and brandName != ''">
- brand_name like #{brandName}
- when>
- choose>
- where>
- select>
-
-
- <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>
-
- <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>
-
- <delete id="deleteById">
-
- delete
- from tb_brand
- where id = #{id};
- delete>
- <delete id="deleteByIds">
- delete
- from tb_brand
- where id in
-
- <foreach collection="ids" item="id" separator="," open="(" close=")">
- #{id}
- foreach>
- ;
- delete>
-
- mapper>
数据库记录也删除成功
