• MyBatis特殊SQL的执行(模糊查询、批量删除、动态设置表名、添加功能获取自增的主键)


    一、模糊查询

    1.1  like '%${xxx}%' 的方式模糊查询

    1. /**
    2. * 根据用户名进行模糊查询
    3. * @param username
    4. * @return java.util.List
    5. */
    6. List<User> getUserByLike(@Param("username") String username);
    1. <!--List<User> getUserByLike(@Param("username") String username);-->
    2. <select id="getUserByLike" resultType="User">
    3. select * from t_user where username like '%${username}%'
    4. </select>

    like '%${xxx}%' 本质上是字符串的拼接,在数据库中单引号表示字符串。此处不能使用#{xxx},#{xxx}的本质是占位符赋值,'%#{xxx}%'会被数据库解析为'%?%',即会去查找字段中是否包含?.

    1.2  like concat('%',#{xxx},'%') 的方式模糊查询

    1. /**
    2. * 根据用户名进行模糊查询
    3. * @param username
    4. * @return java.util.List
    5. */
    6. List<User> getUserByLike(@Param("username") String username);
    1. <!--List<User> getUserByLike(@Param("username") String username);-->
    2. <select id="getUserByLike" resultType="User">
    3. select * from t_user where username like concat('%',#{username},'%')
    4. </select>

    #{}的本质就是占位符赋值,再使用concat()函数进行拼接。

    1.3  "%"#{xxx}"%" 的方式模糊查询(推荐使用)

    此种写法Mysql中有效,Oracle中无效。

    1. /**
    2. * 根据用户名进行模糊查询
    3. * @param username
    4. * @return java.util.List
    5. */
    6. List<User> getUserByLike(@Param("username") String username);
    1. <!--List<User> getUserByLike(@Param("username") String username);-->
    2. <select id="getUserByLike" resultType="User">
    3. select * from t_user where username like "%"#{username}"%"
    4. </select>

    Mysql数据库中,可以使用双引号进行字符串的拼接,如上:"%"#{username}"%"

    • 其中select * from t_user where username like "%"#{xxx}"%"是最常用的

    1.4  '%'||#{xxx}||'%' 

    此种写法Oracle有效,Mysql中无效。

    1. <select id="selectByCondition" resultType="com.chinamobile.zj.modules.aqtz.entity.AqtzTzxxEntity">
    2. select ID,NAME,DEPT_ID,DEPT_NAME,CREAT_TIME,USER_ID,USER_NAME,FILE_ID,PARENT_ID,FILE_NAME,CONTENT from AQTZ_TZXX
    3. <where>
    4. <if test="id != null and id != ''"> and ID = #{id} </if>
    5. <if test="name != null and name != ''"> and NAME like '%'||#{name}||'%' </if>
    6. <if test="deptId != null and deptId != ''"> and DEPT_ID = #{deptId} </if>
    7. <if test="deptName != null and deptName != ''"> and DEPT_NAME like '%'||#{deptName}||'%' </if>
    8. <if test="creatTime != null and creatTime != ''"> and CREAT_TIME like '%'||#{creatTime}||'%' </if>
    9. <if test="userId != null and userId != ''"> and USER_ID = #{userId} </if>
    10. <if test="userName != null and userName != ''"> and USER_NAME like '%'||#{userName}||'%' </if>
    11. <if test="fileId != null and fileId != ''"> and FILE_ID = #{fileId} </if>
    12. <if test="parentId != null and parentId != ''"> and PARENT_ID = #{parentId} </if>
    13. <if test="fileName != null and fileName != ''"> and FILE_NAME like '%'||#{fileName}||'%' </if>
    14. <if test="content != null and content != ''"> and CONTENT like '%'||#{content}||'%' </if>
    15. </where>
    16. </select>

    oracle数据库中,||相当于字符串的拼接。

    二、批量删除

    只能使用${},如果使用#{},则解析后的sql语句为delete from t_user where id in ('1,2,3'),这样是将1,2,3看做是一个整体,只有id为1,2,3的数据会被删除。正确的语句应该是delete from t_user where id in (1,2,3),或者delete from t_user where id in ('1','2','3')
    其中#{xxx}会被解析成 'xxx'.

    1. /**
    2. * 根据id批量删除
    3. * @param ids
    4. * @return int
    5. */
    6. int deleteMore(@Param("ids") String ids);
    1. <delete id="deleteMore">
    2. delete from t_user where id in (${ids})
    3. </delete>
    1. //测试类
    2. @Test
    3. public void deleteMore() {
    4. SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    5. SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
    6. int result = mapper.deleteMore("1,2,3");
    7. System.out.println(result);
    8. }

    三、动态设置表名

    • 只能使用${},因为表名不能加单引号

    其中#{xxx}会被解析成 'xxx'.

    1. /**
    2. * 查询指定表中的数据
    3. * @param tableName
    4. * @return java.util.List
    5. */
    6. List<User> getUserByTable(@Param("tableName") String tableName);
    1. <!--List<User> getUserByTable(@Param("tableName") String tableName);-->
    2. <select id="getUserByTable" resultType="User">
    3. select * from ${tableName}
    4. </select>

    四、添加功能获取自增的主键

    使用场景
    t_clazz(clazz_id,clazz_name)
    t_student(student_id,student_name,clazz_id)
    1.添加班级信息
    2.获取新添加的班级的id
    3.为班级分配学生,即将某学的班级id修改为新添加的班级的id
    在mapper.xml中设置两个属性
    useGeneratedKeys:设置使用自增的主键
    keyProperty:因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参数user对象的某个属性中
     

    1. /**
    2. * 添加用户信息
    3. * @param user
    4. */
    5. void insertUser(User user);
    1. <!--void insertUser(User user);-->
    2. <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
    3. insert into t_user values (null,#{username},#{password},#{age},#{sex},#{email})
    4. </insert>
    1. //测试类
    2. @Test
    3. public void insertUser() {
    4. SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    5. SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
    6. User user = new User(null, "ton", "123", 23, "男", "123@321.com");
    7. mapper.insertUser(user);
    8. System.out.println(user);
    9. //输出:user{id=10, username='ton', password='123', age=23, sex='男', email='123@321.com'},自增主键存放到了user的id属性中
    10. }

  • 相关阅读:
    ECCV2022细粒度图像检索SEMICON学习记录
    .NET餐厅管理系统管理员添加编辑页面前端
    linux 安装 RocketMQ 4.7
    卷积神经网络实现咖啡豆分类 - P7
    node.js-模块化
    LNMP架构
    K8s集群搭建
    Python环境的安装及配置
    物联网水表电子阀工作原理是怎样的?
    开源C# Winform Scada 上位机系统
  • 原文地址:https://blog.csdn.net/weixin_55772633/article/details/132875772