MyBatis高级

2023-09-15 09:58:59

一、动态sql

准备工作:在昨天整合的代码中添加UserMapper接口和配置文件

public interface UserMapper {
    List<User> queryUserByCondition(User user);
}

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatisDTD约束-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linjiu.dao.UserMapper">

    <select id="queryUserByCondition" resultType="com.linjiu.model.User" parameterType="com.linjiu.model.User">
      
    </select>
</mapper>

1、if

  • 格式

    <if test="条件">
        sql 语句
    </if>
    当条件成立的时候,会执行sql语句
    if (条件){
    	sql 语句
    }
    
  • 案例

    <select id="queryUserByCondition" resultType="com.linjiu.model.User" parameterType="com.linjiu.model.User">
        select id,username,password,age,phone from user where 1=1
        <if test="age!=null and age!=''">
            and age=#{age}
        </if>
        <if test="phone!=null and phone!=''">
            and phone=#{phone}
        </if>
    </select>
    
  • java代码

    @Test
    public void test02(){
        User user = new User();
        user.setPhone("120");
        user.setAge(11);
        List<User> users = userMapper.queryUserByCondition(user);
        System.out.println(users);
    }
    
  • 运行日志

    DEBUG [main] - ==> Preparing: select id,username,password,age,phone from user where 1=1 and age=? and phone=?
    DEBUG [main] - ==> Parameters: 11(Integer), 120(String)

2、choose…when…otherwise…

  • 格式

    <choose>
        <when test="条件1"> 
        	sql语句1
        </when>
        
        <when test="条件2"> 
        	sql语句2
        </when>
        
        <otherwise>
            sql语句3
        </otherwise>
    </choose>
    
    和我们java的if...else if ...else格式一样
    当条件1成立,那么就不会执行后面的代码
    
  • 案例

    <select id="queryUserByCondition" resultType="com.linjiu.model.User" parameterType="com.linjiu.model.User">
        select id,username,password,age,phone from user where 1=1
        <choose>
            <when test="age!=null and age!=''">
                and age=#{age}
            </when>
            <when test="phone!=null and phone!=''">
                and phone=#{phone}
            </when>
            <otherwise>
                and password='112233'
            </otherwise>
        </choose>
    </select>
    

3、where

# 说明
	- 标签里边的if 至少有一个成立,就会动态添加一个where,如果都不成立,不添加where 
	- 第一个if条件成立的,会自动去除连接符and 或者 or
	
  • 案例

    <select id="queryUserByCondition" resultType="com.linjiu.model.User" parameterType="com.linjiu.model.User">
        select id,username,password,age,phone from user
        <where>
            <if test="age!=null and age!=''">
                and age=#{age}
            </if>
            <if test="phone!=null and phone!=''">
                and phone=#{phone}
            </if>
        </where>
    </select>
    

4、set

  • 说明

    说明: 动态添加了set字段,也会动态的去掉最后一个逗号
    
  • 案例

    <update id="updateUser" parameterType="com.linjiu.model.User">
        update user
        <set>
            <if test="username!=null and username!=''">username=#{username},</if>
            <if test="password!=null and password!=''">password=#{password},</if>
        </set>
        where id=#{id}
    </update>
    
  • 代码

    @Test
    public void test03(){
        User user = new User();
        user.setId(1);
        user.setUsername("哥哥123");
        user.setPassword("332211");
        String message = userMapper.updateUser(user)>0?"成功":"失败";
        System.out.println(message);
    }
    

5、foreach

  • 说明: 适用于 id in (x,x,x)

  • 格式

    循环遍历标签。适用于多个参数或者的关系。
    <foreach collection=“”open=“”close=“”item=“”separator=“”>
        获取参数
    </foreach>
    
  • 案例

    <select id="queryUsersByIds" resultType="com.linjiu.model.User"
            parameterType="java.lang.Integer">
        select id,username,password,age,phone from user
        <where>
            <foreach collection="list" item="id" open="id in (" close=")" separator=",">
                #{id}
            </foreach>
        </where>
    </select>
    
    
  • 代码

    @Test
    public void test04(){
        ArrayList<Integer> ids = new ArrayList<Integer>();
        Collections.addAll(ids, 1, 2, 3, 4);
        List<User> users = userMapper.queryUsersByIds(ids);
        System.out.println(users);
    }
    

6、trim

  • 格式 pre- presay

    格式 <trim prefix=前缀''   prefixoverrides=''
    	        suffix=后缀''   suffixoverrides=''>
    
  • 替换where

    <select id="queryUserByCondition" resultType="com.linjiu.model.User" parameterType="com.linjiu.model.User">
        select id,username,password,age,phone from user
        <trim prefix="where" prefixOverrides="and">
            <if test="age!=null and age!=''">
                and age=#{age}
            </if>
            <if test="phone!=null and phone!=''">
                and phone=#{phone}
            </if>
        </trim>
    </select>
    
  • 替换set

    <update id="updateUser" parameterType="com.linjiu.model.User">
    
        update user
        <trim prefix="set" suffixOverrides=",">
            <if test="password!=null and password!=''">
                password=#{password},
            </if>
            <if test="age!=null and age!=''">
                age=#{age},
            </if>
        </trim>
        where id=#{id}
    </update>
    

7、Sql片段

  • 格式

    <sql id="别名">
        查询的所有字段
    </sql>
    
    使用的时候 <include refid="别名"/>
    

二、分页

1、分页的使用步骤

1.1、导入maven依赖

<!--        pageHelper依赖-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>0.9.6</version>
        </dependency>

2、mybatis配置文件中指定方言

<plugins>
    <!-- 注意:分页助手的插件  配置在通用mapper之前 -->
    <plugin interceptor="com.github.pagehelper.PageHelper">
        <!-- 指定方言 -->
        <property name="dialect" value="mysql"/>
    </plugin>
</plugins>

3、java代码测试

@Test
public void test02(){

    User user = new User();
    PageHelper.startPage(1, 3);
    List<User> users = userMapper.queryUsersByCondition(user);
    PageInfo<User> pageInfo = new PageInfo<User>(users);

    System.out.println("总条数:"+pageInfo.getTotal());
    System.out.println("总页数:"+pageInfo.getPages());
    System.out.println("当前页:"+pageInfo.getPageNum());
    System.out.println("每页显示长度:"+pageInfo.getPageSize());
    System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
    System.out.println("是否最后一页:"+pageInfo.isIsLastPage());
    List<User> list = pageInfo.getList();
    for (User user1 : list) {
        System.out.println(user1);
    }

}

三、mybatis多表查询

1、一对一

# 步骤
	- 建表  user 和 card
	- 创建实体类 
	- 配置文件
	- 测试
  • 创建实体类
public class Card {
    private int id;
    private String num;
    private User user;
}

CREATE TABLE card (
id int(11) NOT NULL AUTO_INCREMENT,
num varchar(20) DEFAULT NULL,
uid int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

  • 配置文件
<resultMap id="cards" type="com.linjiu.model.Card">
    <id column="id" property="id"></id>
    <result column="num" property="num"></result>
    <association property="user" javaType="com.linjiu.model.User">
        <id column="uid" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="age" property="age"></result>
        <result column="phone" property="phone"></result>
    </association>
</resultMap>


<select id="findAllCard" resultMap="cards">
    select c.id id,num,uid,username,password,age,phone from card c,user u where c.uid=u.id
</select>
  • 标签介绍
<resultMap>:配置数据库库字段和Java对象属性的映射关系标签。
    id 属性:唯一标识
    type 属性:实体对象类型
<id>:配置主键映射关系标签。
<result>:配置非主键映射关系标签。
    column 属性:表中字段名称
    property 属性: 实体对象变量名称
<association>:配置被包含对象的映射关系标签。
    property 属性:被包含对象的变量名
    javaType 属性:被包含对象的数据类型
  • 测试
@Test
public void test05(){
    List<Card> allCard = cardMapper.findAllCard();
    System.out.println(allCard);
}

2、一对多

  • 实体类和表 classes student
package com.linjiu.model;

public class Student {

    private int id;
    private String name;
    private int age;

}

public class Classes {

    private int id;
    private String name;
    private List<Student> students;
}

CREATE TABLE classes (
id int(11) NOT NULL,
name varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE student (
id int(11) NOT NULL,
name varchar(255) DEFAULT NULL,
age int(11) DEFAULT NULL,
cid int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  • 配置文件
<resultMap id="class" type="com.linjiu.model.Classes">
    <id column="id" property="id"></id>
    <result column="name" property="name"></result>
    <collection property="students" ofType="com.linjiu.model.Student">
        <id column="sid" property="id"></id>
        <result column="sage" property="age"></result>
        <result column="sname" property="name"></result>
    </collection>
</resultMap>
<select id="findAll" resultMap="class">
    select c.id id,c.name name,s.id sid,s.name sname,s.age sage from classes c,student s where s.cid=c.id
</select>
  • 标签介绍
<resultMap>:配置字段和对象属性的映射关系标签。
    id 属性:唯一标识
    type 属性:实体对象类型
<id>:配置主键映射关系标签。
<result>:配置非主键映射关系标签。
    column 属性:表中字段名称
    property 属性: 实体对象变量名称
<collection>:配置被包含集合对象的映射关系标签。
    property 属性:被包含集合对象的变量名
    ofType 属性:集合中保存的对象数据类型

3、多对多

3.1、实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student {
    private int id;
    private String name;
    private int age;
    private List<Teacher> teachers;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Teacher {
    private int id;
    private String name;
    private String sex;
    private List<Student> students;
}

3.2、编写mapper

public interface StudentMapper {

    List<Student> findAllStudent();
}

public interface StudentMapper {

    List<Student> findAllStudent();
}

3.3、mapper配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linjiu.dao.StudentMapper">

    <resultMap id="student" type="com.linjiu.model.Student">
        <id property="id" column="sid" />
        <result property="name" column="sname"/>
        <result property="age" column="sage"/>
        <collection property="teachers" ofType="com.linjiu.model.Teacher">
            <id property="id" column="tid" />
            <result property="name" column="tname"/>
            <result property="sex" column="tsex"/>
        </collection>
    </resultMap>

    <select id="findAllStudent" resultMap="student">
        select
            s.id sid,s.name sname,s.age sage,
            t.id tid,t.name tname,t.sex tsex
        from
            teacher t,student s,stu_teach st
        where
            t.id=st.tid and s.id=st.sid
    </select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linjiu.dao.TeachertMapper">

    <resultMap id="teacher" type="com.linjiu.model.Teacher">
        <id property="id" column="tid" />
        <result property="name" column="tname"/>
        <result property="sex" column="tsex"/>
        <collection property="students" ofType="com.linjiu.model.Student">
            <id property="id" column="sid" />
            <result property="name" column="sname"/>
            <result property="age" column="sage"/>
        </collection>
    </resultMap>

    <select id="findAllTeacher" resultMap="teacher">
        select
            t.id tid,t.name tname,t.sex tsex,
            s.id sid,s.name sname,s.age sage
        from
            teacher t,student s,stu_teach st
        where
            t.id=st.tid and s.id=st.sid
    </select>
</mapper>

3.4、测试

@Autowired
private StudentMapper studentMapper;

@Autowired
private TeachertMapper teachertMapper;

@Test
public void test06(){
    List<Student> allStudent = studentMapper.findAllStudent();
    for (Student student : allStudent) {
        String name = student.getName();
        System.out.println(name);
        for (Teacher teacher : student.getTeachers()) {
            System.out.print("\t"+teacher.getName()+"-"+teacher.getSex()+"\t");
        }
        System.out.println();
    }
}
更多推荐

springboot班级综合测评管理系统springboot005

大家好✌!我是CZ淡陌。一名专注以理论为基础实战为主的技术博主,将再这里为大家分享优质的实战项目,本人在Java毕业设计领域有多年的经验,陆续会更新更多优质的Java实战项目,希望你能有所收获,少走一些弯路,向着优秀程序员前行!🍅更多优质项目👇🏻👇🏻可点击下方获取🍅文章底部或评论区获取🍅Java项目精品实

【Docker】华为云服务器安装 Docker 容器

简介Docker是一个开源的应用容器引擎,基于Go语言并遵从Apache2.0协议开源。Docker可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口(类似iPhone的app),更重要的是容器性能开销

海外媒体宣发:海外媒体发稿6种方式方法分享

科学创新在这个时代中起着了至关重要的作用。做为科谱网络写手,大家要不断找到新的专用工具来提高我们自己的文章内容品质和质量。在这篇文章中,我们将给大家分享6个通过美联社检验的发稿神器,帮你的科普文章如鱼得水。1.现状分析专用工具在编写科普文章以前,我们应该对于目标读者背景、兴趣和爱好认知度等方面进行详细分析。那样才能真正

使用结构体组织相关联的数据(5)

使用结构体组织相关联的数据5.使用结构体组织相关关联的数据1.结构体的定义和实例化1.1定义结构体1.2创建结构体的实例1.3使用字段初始化简写语法1.3使用结构体更新语法从其他实例创建实例1.使用旧的实例创建新实例2.\.\.语法创建实例(旧实例为基础)1.4使用没用命名字段的元组结构体来创建不同的类型1.5没有任何

期权开户流程、交易时间和规则详解清晰易懂

本文将介绍期权开户流程、交易时间和规则详解清晰易懂则,包括期权的定义、期权交易的时间、期权交易的规则和期权交易的风险。本文的结论是,期权交易的时间和规则非常重要,应该遵守交易规则,并且要注意风险。本文来源:期权酱券商开通期权账户和期权分仓平台的开户流程是不同的,一般情况如下:一、券商开通期权账户1.投资者需要在有资质的

Python函数绘图与高等代数互溶实例(二): 闪点函数

Python函数绘图与高等代数互溶实例(一):正弦函数与余弦函数Python函数绘图与高等代数互溶实例(二):闪点函数Python函数绘图与高等代数互溶实例(三):设置X|Y轴|网格线一:函数plot(),展示变量的变化趋势importnumpyasnpimportmatplotlib.pyplotaspltfromp

Python和Pandas对事件数据的处理:以电动汽车充电数据为例

1、数据电动汽车的充电数据形式如下订单号充电开始时间充电完成时间订单/时段总充电量(KWh)尖时电量峰时电量平时电量谷时电量2023020105000026122023-02-0100:03:262023-02-0100:40:5228.4410.0000.0000.00028.44120230201050000457

基于vue3 的 Echarts图表展示(任务一:用柱状图展示消费额最高的省份)(操作全流程)(图文版)

目录前言:操作要求:操作流程:一.创建vue项目1.在vscode上创建vue脚手架工程二.配置运行环境2.配置axios(用于访问接口)和引入echarts包3.引入需要用到的js包三.开始实践做题(最后附有完整代码)1.获取接口数据2.数据处理3.echarts图表展示4.最终效果图4.完整参考代码前言:这篇是一个

如何提升网站排名优化(百度SEO优化,轻松提升排名)

在当今互联网时代,拥有一个优秀的网站是很重要的。而一个网站如果能够在搜索引擎上的排名很靠前,那么将会带来更多的流量、更多的用户和更多的利润。那么如何提升网站排名优化呢?蘑菇号www.mooogu.cn百度SEO优化的5个规则1.关键词选取要合理,不要过度堆砌;2.网站结构要简单明了,易于搜索引擎爬取;3.网站内容要原创

Python进阶复习-自带库

目录random库collection库Counter函数namedtuple函数deque函数itertools库enumarate函数zip函数product函数random库random.random():生成一个0到1之间的随机浮点数。random.uniform(a,b):生成一个在a和b之间均匀分布的随机浮

模分多址技术:Model division multiple access for semantic communications

目录论文简介知识积累模分多址论文简介作者PingZhang(张平)XiaodongXu(许晓东)ChenDong(董辰)KaiNiu(牛凯)发表期刊or会议《FrontiersofInformationTechnology&ElectronicEngineering》发表时间2023.6知识积累多址技术主要致力于将正交

热文推荐