MyBatis高级

文章目录

一、动态sql

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

java 复制代码
public interface UserMapper {
    List<User> queryUserByCondition(User user);
}

<?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.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

markdown 复制代码
# 说明
	- 标签里边的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)

  • 格式

    xml 复制代码
    循环遍历标签。适用于多个参数或者的关系。
    <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

    xml 复制代码
    格式 <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、一对一

markdown 复制代码
# 步骤
	- 建表  user 和 card
	- 创建实体类 
	- 配置文件
	- 测试
  • 创建实体类
java 复制代码
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>
  • 标签介绍

markdown 复制代码
<resultMap>:配置数据库库字段和Java对象属性的映射关系标签。
    id 属性:唯一标识
    type 属性:实体对象类型
<id>:配置主键映射关系标签。
<result>:配置非主键映射关系标签。
    column 属性:表中字段名称
    property 属性: 实体对象变量名称
<association>:配置被包含对象的映射关系标签。
    property 属性:被包含对象的变量名
    javaType 属性:被包含对象的数据类型
  • 测试
java 复制代码
@Test
public void test05(){
    List<Card> allCard = cardMapper.findAllCard();
    System.out.println(allCard);
}

2、一对多

  • 实体类和表 classes student
java 复制代码
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>
  • 标签介绍

xml 复制代码
<resultMap>:配置字段和对象属性的映射关系标签。
    id 属性:唯一标识
    type 属性:实体对象类型
<id>:配置主键映射关系标签。
<result>:配置非主键映射关系标签。
    column 属性:表中字段名称
    property 属性: 实体对象变量名称
<collection>:配置被包含集合对象的映射关系标签。
    property 属性:被包含集合对象的变量名
    ofType 属性:集合中保存的对象数据类型

3、多对多

3.1、实体类

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

3.2、编写mapper

java 复制代码
public interface StudentMapper {

    List<Student> findAllStudent();
}

public interface StudentMapper {

    List<Student> findAllStudent();
}

3.3、mapper配置文件

xml 复制代码
<?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 复制代码
<?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、测试

java 复制代码
@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();
    }
}
相关推荐
真实的菜几秒前
Java NIO 面试全解析:9大核心考点与深度剖析
java·面试·nio
飞翔的佩奇16 分钟前
Java项目:基于SSM框架实现的劳务外包管理系统【ssm+B/S架构+源码+数据库+毕业论文】
java·mysql·spring·毕业设计·ssm·毕业论文·劳务外包
luckywuxn31 分钟前
EurekaServer 工作原理
java·eureka
壹米饭34 分钟前
Java程序员学Python学习笔记一:学习python的动机与思考
java·后端·python
java金融36 分钟前
Java 锁升级机制详解
java
Young556640 分钟前
还不了解工作流吗(基础篇)?
java·workflow·工作流引擎
让我上个超影吧41 分钟前
黑马点评【缓存】
java·redis·缓存
ajassi20001 小时前
开源 java android app 开发(十一)调试、发布
android·java·linux·开源
YuTaoShao1 小时前
Java八股文——MySQL「存储引擎篇」
java·开发语言·mysql
crud1 小时前
Java 中的 synchronized 与 Lock:深度对比、使用场景及高级用法
java