• SSM33:MYBatis注解开发


      目录

    单条件查询

    数据库表(tb_brand)及数据准备

    实体类 Brand

    编写测试用例

    下载MybatisX插件

    查询所有数据思路

    创建名为 BrandMapper.java接口

    编写测试方法MybatisTest 类

    编写BrandMapper.xml

    运行结果


    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)及数据准备

    1. -- 删除tb_brand表
    2. drop table if exists tb_brand;
    3. -- 创建tb_brand表
    4. create table tb_brand
    5. (
    6. -- id 主键
    7. id int primary key auto_increment,
    8. -- 品牌名称
    9. brand_name varchar(20),
    10. -- 企业名称
    11. company_name varchar(20),
    12. -- 排序字段
    13. ordered int,
    14. -- 描述信息
    15. description varchar(100),
    16. -- 状态:0:禁用 1:启用
    17. status int
    18. );
    19. -- 添加数据
    20. insert into tb_brand (brand_name, company_name, ordered, description, status)
    21. values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
    22. ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
    23. ('小米', '小米科技有限公司', 50, 'are you ok',

    实体类 Brand

    com.itheima.pojo 包下创建 Brand 实体类。

    1. public class Brand {
    2. // id 主键
    3. private Integer id;
    4. // 品牌名称
    5. private String brandName;
    6. // 企业名称
    7. private String companyName;
    8. // 排序字段
    9. private Integer ordered;
    10. // 描述信息
    11. private String description;
    12. // 状态:0:禁用 1:启用
    13. private Integer status;
    14. //省略 setter and getter。自己写时要补全这部分代码
    15. }

    编写测试用例

    测试代码需要在 test/java 目录下创建包及测试用例。项目结构如下:

    1. package com.itheima.test;
    2. public class MybatisTest {
    3. }

    下载MybatisX插件

    • MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。

    • 主要功能

      • XML映射配置文件 和 接口方法 间相互跳转

      • 根据接口方法生成 statement

    • 安装方式

    重启一下

     

     红色头绳的表示映射配置文件,蓝色头绳的表示mapper接口。在mapper接口点击红色头绳的小鸟图标会自动跳转到对应的映射配置文件,在映射配置文件中点击蓝色头绳的小鸟图标会自动跳转到对应的mapper接口。也可以在mapper接口中定义方法,自动生成映射配置文件中的 statement

    查询所有数据思路

    • 编写接口方法:Mapper接口

      • 参数:无

        查询所有数据功能是不需要根据任何条件进行查询的,所以此方法不需要参数。

      • 结果:List

        我们会将查询出来的每一条数据封装成一个 Brand 对象,而多条数据封装多个 Brand 对象,需要将这些对象封装到List集合中返回。

      • 执行方法、测试

    创建名为 BrandMapper.java接口

    com.itheima.mapper 包写创建名为 BrandMapper 的接口。并在该接口中定义 List selectAll() 方法。

    1. package com.itheima.mapper;
    2. import com.itheima.pojo.Brand;
    3. import org.apache.ibatis.annotations.Param;
    4. import org.apache.ibatis.annotations.Select;
    5. import java.util.List;
    6. import java.util.Map;
    7. public interface BrandMapper {
    8. //查询所有的方法
    9. @Select("select * from tb_brand")
    10. public List selectAll();
    11. //按照id查找信息
    12. Brand selectById(int id);
    13. //有条件查询三种方法
    14. List selectByCondition(@Param("status") int status,
    15. @Param("companyName") String companyName,
    16. @Param("brandName") String brandName);
    17. // List selectByCondition(Brand brand);
    18. List selectByCondition(Map map);
    19. //单条件查询
    20. List selectByConditionSingle(Brand brand);
    21. //添加功能·
    22. void add(Brand brand);
    23. //动态修改
    24. int update(Brand brand);
    25. //删除一条记录
    26. void deleteById(int id);
    27. //批量删除
    28. void deleteByIds(@Param("ids")int[] ids);
    29. }

    编写测试方法MybatisTest

    1. package com.itheima.test;
    2. import com.itheima.mapper.BrandMapper;
    3. import com.itheima.pojo.Brand;
    4. import org.apache.ibatis.io.Resources;
    5. import org.apache.ibatis.session.SqlSession;
    6. import org.apache.ibatis.session.SqlSessionFactory;
    7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    8. import org.junit.Test;
    9. import java.io.IOException;
    10. import java.io.InputStream;
    11. import java.util.HashMap;
    12. import java.util.List;
    13. import java.util.Map;
    14. public class MybatisTest {
    15. //1.查询所有
    16. @Test
    17. public void testSelecctAll() throws IOException {
    18. String resource = "mybatis-config.xml";
    19. InputStream inputStream = Resources.getResourceAsStream(resource);
    20. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    21. SqlSession sqlSession = sqlSessionFactory.openSession();
    22. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    23. List brands = brandMapper.selectAll();
    24. System.out.println(brands);
    25. sqlSession.close();
    26. }
    27. //2.查询详细
    28. @Test
    29. public void testSelecctByIdl() throws IOException {
    30. int id = 1;
    31. String resource = "mybatis-config.xml";
    32. InputStream inputStream = Resources.getResourceAsStream(resource);
    33. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    34. SqlSession sqlSession = sqlSessionFactory.openSession();
    35. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    36. //改变sql语句
    37. Brand brand = brandMapper.selectById(id);
    38. System.out.println(brand);
    39. sqlSession.close();
    40. }
    41. //3.多条件查询
    42. @Test
    43. public void testselectByCondition() throws IOException {
    44. int status = 1;
    45. String companyName = "华为";
    46. String brandName = "华为";
    47. //数据处理
    48. companyName = "%" + companyName + "%";
    49. brandName = "%" + brandName + "%";
    50. /* Brand brand = new Brand();
    51. brand.setStatus(status);
    52. brand.setCompanyName(companyName);
    53. brand.setBrandName(brandName);*/
    54. //List brands = brandMapper.selectByCondition(brand);
    55. String resource = "mybatis-config.xml";
    56. InputStream inputStream = Resources.getResourceAsStream(resource);
    57. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    58. SqlSession sqlSession = sqlSessionFactory.openSession();
    59. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    60. //方式三 :接口方法参数是 map集合对象 方式调用的方法
    61. Map map = new HashMap();
    62. // map.put("status" , status);
    63. map.put("companyName", companyName);
    64. // map.put("brandName" , brandName);
    65. //改变sql语句
    66. List brands = brandMapper.selectByCondition(map);
    67. System.out.println(brands);
    68. // List brands = brandMapper.selectByCondition(status, companyName, brandName);
    69. System.out.println(brands);
    70. sqlSession.close();
    71. }
    72. //4.单条件查询
    73. @Test
    74. public void testselectByConditionSingle() throws IOException {
    75. int status = 1;
    76. String companyName = "华为";
    77. String brandName = "华为";
    78. //数据处理
    79. companyName = "%" + companyName + "%";
    80. brandName = "%" + brandName + "%";
    81. Brand brand = new Brand();
    82. brand.setStatus(status);
    83. // brand.setCompanyName(companyName);
    84. // brand.setBrandName(brandName);
    85. //List brands = brandMapper.selectByCondition(brand);
    86. String resource = "mybatis-config.xml";
    87. InputStream inputStream = Resources.getResourceAsStream(resource);
    88. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    89. SqlSession sqlSession = sqlSessionFactory.openSession();
    90. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    91. //改变sql语句
    92. List brands = brandMapper.selectByConditionSingle(brand);
    93. System.out.println(brands);
    94. sqlSession.close();
    95. }
    96. //5.普通添加功能
    97. @Test
    98. public void testadd() throws IOException {
    99. int status = 1;
    100. String companyName = "刘德华品牌手机";
    101. String brandName = "红米";
    102. String description = "号的中国制造";
    103. int order = 100;
    104. //数据处理
    105. // companyName="%"+companyName+"%";
    106. // brandName="%"+brandName+"%";
    107. Brand brand = new Brand();
    108. brand.setStatus(status);
    109. brand.setCompanyName(companyName);
    110. brand.setBrandName(brandName);
    111. brand.setDescription(description);
    112. brand.setOrdered(order);
    113. //List brands = brandMapper.selectByCondition(brand);
    114. String resource = "mybatis-config.xml";
    115. InputStream inputStream = Resources.getResourceAsStream(resource);
    116. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    117. SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
    118. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    119. //改变sql语句
    120. brandMapper.add(brand);
    121. Integer id = brand.getId();
    122. System.out.println(id);
    123. //提交事务
    124. // sqlSession.commit();
    125. //关闭资源
    126. sqlSession.close();
    127. }
    128. //6.动态修改功能
    129. @Test
    130. public void testupdate() throws IOException {
    131. int status = 1;
    132. String companyName = "kk";
    133. String brandName = "kk";
    134. String description = "号的中国制造";
    135. int order = 100;
    136. int id=5;
    137. //数据处理
    138. // companyName="%"+companyName+"%";
    139. // brandName="%"+brandName+"%";
    140. Brand brand = new Brand();
    141. brand.setStatus(status);
    142. brand.setCompanyName(companyName);
    143. brand.setBrandName(brandName);
    144. // brand.setDescription(description);
    145. // brand.setOrdered(order);
    146. brand.setId(id);
    147. //List brands = brandMapper.selectByCondition(brand);
    148. String resource = "mybatis-config.xml";
    149. InputStream inputStream = Resources.getResourceAsStream(resource);
    150. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    151. SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
    152. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    153. //改变sql语句
    154. int count = brandMapper.update(brand);
    155. System.out.println(count);
    156. //提交事务
    157. // sqlSession.commit();
    158. //关闭资源
    159. sqlSession.close();
    160. }
    161. //删除一条记录
    162. @Test
    163. public void testdeleteById() throws IOException {
    164. int id=5;
    165. //数据处理
    166. // companyName="%"+companyName+"%";
    167. // brandName="%"+brandName+"%";
    168. //List brands = brandMapper.selectByCondition(brand);
    169. String resource = "mybatis-config.xml";
    170. InputStream inputStream = Resources.getResourceAsStream(resource);
    171. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    172. SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
    173. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    174. //改变sql语句
    175. brandMapper.deleteById(id);
    176. //提交事务
    177. // sqlSession.commit();
    178. //关闭资源
    179. sqlSession.close();
    180. }
    181. //批量删除
    182. @Test
    183. public void testdeleteByIds() throws IOException {
    184. int[] ids={6,7,8};
    185. //数据处理
    186. // companyName="%"+companyName+"%";
    187. // brandName="%"+brandName+"%";
    188. //List brands = brandMapper.selectByCondition(brand);
    189. String resource = "mybatis-config.xml";
    190. InputStream inputStream = Resources.getResourceAsStream(resource);
    191. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    192. SqlSession sqlSession = sqlSessionFactory.openSession(true);//代表提交事务
    193. BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    194. //改变sql语句
    195. brandMapper.deleteByIds(ids);
    196. //提交事务
    197. // sqlSession.commit();
    198. //关闭资源
    199. sqlSession.close();
    200. }
    201. }

    编写BrandMapper.xml

    1. "1.0" encoding="UTF-8" ?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.itheima.mapper.BrandMapper">
    6. <resultMap id="brandresultMapper" type="brand">
    7. <result column="brand_Name" property="brandName"/>
    8. <result column="company_Name" property="companyName"/>
    9. resultMap>
    10. <select id="selectAll" resultMap="brandresultMapper">
    11. select * from tb_brand;
    12. select>
    13. <select id="selectById" resultMap="brandresultMapper">
    14. select *
    15. from tb_brand
    16. where id = #{id};
    17. select>
    18. <select id="selectByCondition" resultMap="brandresultMapper">
    19. select *
    20. from tb_brand
    21. <where>
    22. <if test="status!=null">
    23. and status = #{status}
    24. if>
    25. <if test="company_name!=null and company_name !='' ">
    26. and company_name like #{companyName}
    27. if>
    28. <if test="brandName!=null and brandName!='' ">
    29. and brand_name like #{brandName}
    30. if>
    31. where>
    32. select>
    33. <select id="selectByConditionSingle" resultMap="brandresultMapper">
    34. select *
    35. from tb_brand
    36. <where>
    37. <choose>
    38. <when test="status != null">
    39. status = #{status}
    40. when>
    41. <when test="companyName != null and companyName != '' ">
    42. company_name like #{companyName}
    43. when>
    44. <when test="brandName != null and brandName != ''">
    45. brand_name like #{brandName}
    46. when>
    47. choose>
    48. where>
    49. select>
    50. <insert id="add" useGeneratedKeys="true" keyProperty="id">
    51. insert into tb_brand (brand_name, company_name, ordered, description, status)
    52. values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
    53. insert>
    54. <update id="update">
    55. update tb_brand
    56. <set>
    57. <if test="brandName != null and brandName != ''">
    58. brand_name = #{brandName},
    59. if>
    60. <if test="companyName != null and companyName != ''">
    61. company_name = #{companyName},
    62. if>
    63. <if test="ordered != null">
    64. ordered = #{ordered},
    65. if>
    66. <if test="description != null and description != ''">
    67. description = #{description},
    68. if>
    69. <if test="status != null">
    70. status = #{status}
    71. if>
    72. set>
    73. where id = #{id};
    74. update>
    75. <delete id="deleteById">
    76. delete
    77. from tb_brand
    78. where id = #{id};
    79. delete>
    80. <delete id="deleteByIds">
    81. delete
    82. from tb_brand
    83. where id in
    84. <foreach collection="ids" item="id" separator="," open="(" close=")">
    85. #{id}
    86. foreach>
    87. ;
    88. delete>
    89. mapper>

    运行结果

    数据库记录也删除成功 

  • 相关阅读:
    Docker 01 概述
    Debian12系统下LAMP环境中Nubuilder4.5的安装
    算法小记【1】
    使用ssl_certificate_by_lua指令动态加载证书
    【Mongodb数据库】的介绍和安装(windows下和ubuntu16.04下安装及启动)
    京鸿鑫源元宇宙革新探索:开启未来零售新纪元
    J2EE基础:MySQL01
    《进阶篇第9章》学习vuex知识点后练习:求和案例_纯vue版代码
    日志门面技术
    LeetCode 0086.分隔链表
  • 原文地址:https://blog.csdn.net/weixin_51330376/article/details/127541980