mybatis xml多表查询,子查询,连接查询,动态sql

3 篇文章 0 订阅
2 篇文章 0 订阅

项目结构

在这里插入图片描述

数据库表

student_type 表

在这里插入图片描述

student 表

在这里插入图片描述

依赖

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

实体类

Student 类

一个学生只有一个年级

package com.tmg.domain;

public class Student {
    private int id;
    private String name;
    private int age;
    private String email;
    private Integer typeId;
    private Type type;

    public Integer getTypeId() {
        return typeId;
    }

    public void setTypeId(Integer typeId) {
        this.typeId = typeId;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Student(int id, String name, int age, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public Student() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", typeId=" + typeId +
//                ", type=" + type +
                '}';
    }
}

Type 类

一个年级有多个学生,所以用 list

package com.tmg.domain;

import java.util.List;

public class Type {
    private Integer id;
    private String name;
    private List<Student> students;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Type{" +
                "id=" + id +
                ", name='" + name + '\'' +
//                ", students=" + students +
                '}';
    }
}

StudentDao

package com.tmg.dao;

import com.tmg.domain.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface StudentDao {


    //多个参数的配置
    void insertEmp( @Param("stuName")  String name,
                   @Param("stuAge") int age, @Param("stuEmail")  String email);

    List<Student> selectByStudent(Student student);

    void update(Student employee);

    void update2(Student employee);

    List<Student> selectByIds(@Param("ids") int []id);
//    List<Student> selectById(int id);

    List<Student> selectByTypeId(int id);
    List<Student> selectAll();
}

TypeDao

package com.tmg.dao;

import com.tmg.domain.Type;

import java.util.List;

public interface TypeDao {

    List<Type> selectAll();

    Type  selectById(Integer id);
}

mybatis-config.xml配置数据源,日志等

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    dddd-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="ture"/><!--配置下划线转换为驼峰命名风格-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager><!--事务管理器-->
            <dataSource type="POOLED"><!--数据源 POOLED代表池化-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="dao/StudentDao.xml"></mapper>
        <mapper resource="dao/TypeDao.xml"></mapper>
    </mappers>
</configuration>

TypeDao.xml

下列代码中:
1 resultMap 里面property对应实体类属性,column对应数据库字段名
2 主键用 id 标签 其他用result
3 关联查询(子查询和连接查询) 连接查询查一次
4 一个年级多个学生,所以用collection 如果一对一用association

<?xml version="1.0" encoding="UTF-8" ?>

<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tmg.dao.TypeDao">
    <resultMap id="typeMap" type="com.tmg.domain.Type">
        <id property="id" column="type_id"></id>
        <result property="name" column="type_name"></result>
<!--        连接查询-->
<!--        <collection property="students"-->
<!--                    javaType="java.util.List" ofType="com.tmg.domain.Student">-->
<!--            <id property="id" column="stu_id" javaType="java.lang.Integer"></id>-->
<!--            <result property="name" column="stu_name"></result>-->
<!--            <result property="age" column="stu_age"></result>-->
<!--            <result property="email" column="stu_email"></result>-->
<!--        </collection>-->

<!--        子查询-->
        <collection property="students" column="type_id"
                    javaType="java.util.List" ofType="com.tmg.domain.Student"
                    select="com.tmg.dao.StudentDao.selectByTypeId">

        </collection>
<!-- property 实体类中的属性名 column 子查询使用的字段 javaType 集合类型  ofType 集合里面的泛型类型-->
    </resultMap>
    <select id="selectAll" resultMap="typeMap">
        select s.*,t.* from student s join student_type t on s.type_id=t.type_id
    </select>

    <select id="selectById" resultMap="typeMap">
        select * from student_type where type_id=#{id}
    </select>


</mapper>

StudentDao.xml

动态sql不理解可看以下博客:
https://blog.csdn.net/weixin_57689217/article/details/135707991?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22135707991%22%2C%22source%22%3A%22weixin_57689217%22%7D

<?xml version="1.0" encoding="UTF-8" ?>

<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射的命名空间 = 包名+接口类-->
<mapper namespace="com.tmg.dao.StudentDao">
    <!--配置insert操作 id是方法名 parameterType是参数类型  #{属性名}用于读取对象的属性值-->
    <!--#{}和${}的区别,#{}相当于PreparedStatement的占位符?提前编译,避免SQL注入 ${}是Statement字符串拼接,不能避免注入 -->
    <!--获得最新的自增主键值 useGeneratedKeys=true keyProperty主键的属性-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into student( id,name,age,email) values (#{id},#{name},#{age},#{email});
    </insert>

<!--    问题:查询出的名称为多个单词的字段出现null值-->
<!--    原因:数据库的字段单词以下划线分隔,Java的属性以驼峰命名,导致部分名称不一致无法实现映射-->
    <select id="selectAll" resultMap="student">
        select * from student
    </select>

    <resultMap id="student" type="com.tmg.domain.Student">
        <!--配置主键 property是java属性名 column是表字段名-->
        <id property="id" column="stu_id" javaType="java.lang.Integer"></id>
        <!--普通字段-->
        <result property="name" column="stu_name"></result>
        <result property="age" column="stu_age"></result>
        <result property="email" column="stu_email"></result>
        <result property="typeId" column="type_id"></result>

<!--        <association property="type"-->
<!--                     javaType="com.tmg.domain.Type">-->
<!--            <id property="id" column="type_id"></id>-->
<!--            <result property="name" column="type_name"></result>-->
<!--        </association>-->
        <association property="type" column="type_id"
                     javaType="com.tmg.domain.Type"
                     select="com.tmg.dao.TypeDao.selectById">

        </association>
    </resultMap>


<!--    动态sql-->
<sql id="mySelect">
    select * from student
</sql>
    <select id="selectByStudent" parameterType="com.tmg.domain.Student" resultType="com.tmg.domain.Student" resultMap="student">
        <include refid="mySelect"></include>
        <where>
            <if test="name !=null">

                stu_name like "%"#{name}"%"
            </if>
            <if test="age !=null and age!=0">
                and stu_age=#{age}
            </if>
            <if test="email !=null">
                and stu_email=#{email}
            </if>
        </where>
    </select>

    <update id="update">
        update student
        <set>
            <if test="age !=null and age!=0">
                stu_age=#{age},
            </if>
            <if test="email!=null">
                stu_email=#{email},
            </if>
            <if test="name">
                stu_name=#{name},
            </if>
        </set>
        where stu_id=#{id};
    </update>
    <update id="update2">
        update student
        <trim prefix="set" suffixOverrides=",">
            <if test="age !=null and age!=0">
                stu_age=#{age},
            </if>
            <if test="email!=null">
                stu_email=#{email},
            </if>
            <if test="name">
                stu_name=#{name},
            </if>
        </trim>
        where stu_id=#{id};
    </update>

    <select id="selectByIds" resultMap="student">
        select s.*,t.* from student s join student_type t on s.type_id=t.type_id
        where stu_id in
        <foreach collection="ids" item="id" separator="," open="(" close=")" index="1">
            #{id}
        </foreach>
    </select>

    <select id="selectByTypeId" resultMap="student">
        <include refid="mySelect"></include> where type_id=#{id}
    </select>



</mapper>

TypeDaoText 测试类

package com.tmg.dao;

import com.tmg.domain.Type;
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.util.List;

public class TypeDaoText {
    @Test
    public void testselectAll() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        TypeDao mapper = sqlSession.getMapper(TypeDao.class);
        List<Type> typeList = mapper.selectAll();
        for (Type type : typeList) {
            System.out.println(type);
        }
    }


    @Test
    public void testselectById() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        TypeDao mapper = sqlSession.getMapper(TypeDao.class);
        Type type = mapper.selectById(1);
        System.out.println(type);
    }
}

StudentDaoText 测试类

package com.tmg.dao;

import com.tmg.domain.Student;
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.util.List;

public class StudentDaoText {

    @Test
    public void testinsertEmp() throws IOException {
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = factory.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        mapper.insertEmp("tmg",18,"tmg@qq.com");
        sqlSession.commit();
    }

    @Test
    public void testselectByStudent() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();
//        student.setName("z");
//        student.setAge(18);
//        student.setEmail("tmg@qq.com");
        List<Student> students = mapper.selectByStudent(student);
        for (Student student1 : students){
            System.out.println(student1);
        }
    }
    @Test
    public void testupdate() throws IOException {
        //创建会话工厂构建器
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        //创建会话
        SqlSession sqlSession = build.openSession();
        //获得Mapper对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();
//        student.setName();
        student.setId(1);
        student.setAge(22);
        mapper.update(student);
        sqlSession.commit();
    }
    @Test
    public void testupdate2() throws IOException {
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();
        student.setId(1);
        student.setAge(44);
        mapper.update2(student);
        sqlSession.commit();
    }

    @Test
    public void testselectByIds() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        int []a={1};
        List<Student> students = mapper.selectByIds(a);
        for (Student student:students){
            System.out.println(student);
            System.out.println(student.getType());
        }
    }
    @Test
    public void testselectAll() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        List<Student> students = mapper.selectAll();
        for(Student student : students){
            System.out.println(student);
            System.out.println(student.getType());
        }

    }
}

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果要使用 Mybatis 实现动态递归菜单查询 SQL,可以使用 Mybatis 的递归查询功能和动态 SQL 功能来实现。 下面是一个示例 SQL,可以根据传入的菜单 ID 查询该菜单及其所有子菜单: ``` WITH RECURSIVE temp_menu(id, parent_id, name, level, path) AS ( -- 查询指定菜单 SELECT id, parent_id, name, 1 AS level, CAST(id AS VARCHAR) AS path FROM menu WHERE id = #{menuId} UNION ALL -- 查询子菜单 SELECT m.id, m.parent_id, m.name, tm.level + 1 AS level, CONCAT(tm.path, '-', m.id) AS path FROM menu m INNER JOIN temp_menu tm ON m.parent_id = tm.id ) SELECT id, parent_id, name, level, path FROM temp_menu ORDER BY path; ``` 在这个 SQL 中,使用了 WITH RECURSIVE 子句和 UNION ALL 操作符来实现递归查询查询出指定菜单及其所有子菜单。其中,temp_menu 是一个递归查询的临时表,用于存储查询结果,包含了菜单 ID、菜单名称、菜单级别和菜单路径等信息。使用了 CAST 和 CONCAT 函数来处理菜单路径。 在 Mybatis 中,可以使用 #{menuId} 占位符来接收传入的菜单 ID 参数,然后编写对应的 Mapper 接口和 XML 文件,使用动态 SQL 功能来拼接 SQL 语句,最终实现动态递归菜单查询。 例如,对应的 Mapper 接口和 XML 文件如下: ``` public interface MenuMapper { List<Menu> selectRecursiveMenu(Integer menuId); } ``` ``` <!-- MenuMapper.xml --> <select id="selectRecursiveMenu" resultMap="menuResultMap"> WITH RECURSIVE temp_menu(id, parent_id, name, level, path) AS ( -- 查询指定菜单 SELECT id, parent_id, name, 1 AS level, CAST(id AS VARCHAR) AS path FROM menu WHERE id = #{menuId} UNION ALL -- 查询子菜单 SELECT m.id, m.parent_id, m.name, tm.level + 1 AS level, CONCAT(tm.path, '-', m.id) AS path FROM menu m INNER JOIN temp_menu tm ON m.parent_id = tm.id ) SELECT id, parent_id, name, level, path FROM temp_menu ORDER BY path; </select> ``` 在 XML 文件中,使用了 select 语句来定义 SQL 查询语句,并使用 resultMap 来映射查询结果集。使用了 #{menuId} 占位符来接收传入的菜单 ID 参数,并在 SQL 语句中使用动态 SQL 语句拼接查询语句。最后,定义了一个 selectRecursiveMenu 方法来调用该 SQL 语句,并返回查询结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值