代码编织梦想

目录

层级结构

Mapper接口

IdCardMapper

 OrderMapper

ProductMapper

UsersMapper

 pojo实体类

IdCard

Order

 Product

 工具类:

MybatisUtil

 映射文件***Mapper.xml

IdCardMapper

OrderMapper

 ProductMapper

UsersMapper

 Test测试

 mybatis-config.xml

 数据库文件


层级结构

 

 java层中、resources层 及 test测试建议层级结构相同

这样生成的target看起来一目了然!

Mapper接口

IdCardMapper

public interface IdCardMapper {
    Idcard findIdcardById(int id);
}

 OrderMapper

public interface OrderMapper {
    List<Order> findOrdersByUserId(int id);
    Order findOrderById(int id);
    Order findOrderById2(int id);
}

ProductMapper

public interface ProductMapper {
    Product findProductbyId(int pdId);
}

UsersMapper

public interface UsersMapper {
    Users findUsersById(int id);
    Users findUsersById2(int id);

    Users findUserOrder(int id);
    Users findUserOrder1(int id);
}

 pojo实体类

//  这里因为引入了lombok依赖,所以为了简便直接写的Data注释不建议

IdCard

@Data
public class Idcard {
    private Integer id;
    private String code;

}

Order

@Data
public class Order {
    int or_id;
    String order_num ;
    int user_id;
    List<Product> productList;
}

 Product

@Data
public class Product {
    int  pd_id;
    String book_name;
    double price;
    List<Order> orderList;

}

@Data
public class Users {
    int uid ;
    String uname;
    int uage;
    String usex;
    Idcard uidcard;
    List<Order> orderList;

}

 工具类:

MybatisUtil

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        Reader resourceAsReader = null;
        try {
            resourceAsReader = Resources.getResourceAsReader("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);

    }

    public static SqlSession geSqlSession(){
//        直接提交事务
        return sqlSessionFactory.openSession(true);
    }
}

 映射文件***Mapper.xml

IdCardMapper

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--        修改为IdCard的映射文件路径-->
<mapper namespace="com.gcx.Mapper.IdCardMapper">

    <select id="findIdcardById" resultType="com.gcx.pojo.Idcard">
        select * from mybatis.tb_idcard where id = #{id}
    </select>
</mapper>

OrderMapper

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--        修改为Order的映射文件路径-->
<mapper namespace="com.gcx.Mapper.OrderMapper">

    <select id="findOrdersByUserId" resultType="com.gcx.pojo.Order">
        select *
        from mybatis.tb_orders
        where user_id = #{id}
    </select>


    <!--   map-->
    <select id="findOrderById" resultMap="FindOrderByIdMap">
        select *
        from mybatis.tb_orders
        where user_id = #{id}
    </select>
    <resultMap id="FindOrderByIdMap" type="com.gcx.pojo.Order">
        <id property="or_id" column="or_id"/>
        <result property="order_num" column="order_num"/>
        <collection property="productList" column="or_id" select="com.yiwu.mapper.ProductMapper.findProductbyId"/>
    </resultMap>


    <select id="findOrderById2" resultMap="findOrderById2Map">
        select o.*, p.*
        from mybatis.tb_orders o,
             mybatis.tb_product p,
             mybatis.tb_ordersitem op
        where o.or_id = #{id}
          and op.or_id = o.or_id
          and op.pd_id = p.pd_id
    </select>
    <resultMap id="findOrderById2Map" type="com.gcx.pojo.Order">
        <id property="or_id" column="or_id"/>
        <result property="order_num" column="order_num"/>
        <!--        返回集合-->
        <collection property="productList" ofType="com.gcx.pojo.Product">
            <id property="pd_id" column="pd_id"/>
            <result property="book_name" column="book_name"/>
            <result property="price" column="price"/>
        </collection>
    </resultMap>
</mapper>

 

 ProductMapper

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--        修改为Product的映射文件路径-->
<mapper namespace="com.gcx.Mapper.ProductMapper">
    <select id="findProductbyId" resultType="com.gcx.pojo.Product">
<!--查找并根据tb_ordersitem表中的pd_id查找对应的tb_product中的pd_id所有-->
        select* from mybatis.tb_product where pd_id in (select pd_id from mybatis.tb_ordersitem where or_id = #{or_id})
    </select>
</mapper>

UsersMapper

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--        修改映射文件路径-->
<mapper namespace="com.gcx.Mapper.UsersMapper">



    <select id="findUsersById" resultMap="findIdCardByIDMapper">
        select * from mybatis.tb_user where uid = #{uid}
    </select>
    <resultMap id="findIdCardByIDMapper" type="com.gcx.pojo.Users">
        <association property="uidcard" column="ucard_id" select="com.gcx.mapper.IdCardMapper.findIdcardById"/>
    </resultMap>

    <select id="findUsersById2" resultMap="findIdCardByIDMapper2">
        select u.*,card.id as cardID,card.code as ucard from mybatis.tb_user u,mybatis.tb_idcard  card where u.uid = #{uid} and u.ucard_id = card.id
    </select>
    <resultMap id="findIdCardByIDMapper2" type="com.gcx.pojo.Users">
        <id property="uid" column="uid"/>
        <result property="uname" column="uanme"/>
        <result property="uage" column="uage"/>
        <result property="usex" column="usex"/>
        <association property="uidcard" javaType="com.gcx.pojo.Idcard">
            <id property="id" column="cardID"/>
            <result property="code" column="ucard"/>
        </association>
    </resultMap>

    <select id="findUserOrder" resultMap="findUserOrderMapper">
        select *
        from mybatis.tb_user
        where uid = #{uid};
    </select>
    <resultMap id="findUserOrderMapper" type="com.gcx.pojo.Users">
        <id property="uid" column="uid"/>
        <result property="uname" column="uanme"/>
        <result property="uage" column="uage"/>
        <result property="usex" column="usex"/>
        <collection property="orderList" column="uid" select="com.yiwu.mapper.OrderMapper.findOrdersByUserId"/>
    </resultMap>

    <select id="findUserOrder1" resultMap="findUserOrderMapper2">
        select u.*,o.*
        from mybatis.tb_user u,mybatis.tb_orders o
        where u.uid = #{id} and o.user_id = u.uid
    </select>
    <resultMap id="findUserOrderMapper2" type="com.gcx.pojo.Users">
        <id property="uid" column="uid"/>
        <result property="uname" column="uanme"/>
        <result property="uage" column="uage"/>
        <result property="usex" column="usex"/>
        <collection property="orderList" ofType="com.gcx.pojo.Order">
            <id property="or_id" column="or_id"/>
            <result property="order_num" column="order_num"/>
        </collection>
    </resultMap>
</mapper>

 Test测试

public class UserTest {
//    定义全局变量
    private UsersMapper mapper;
    private SqlSession sqlSession;
    private OrderMapper mappers;


    @Before
    public void before(){
        sqlSession = MybatisUtil.geSqlSession();
        mapper = sqlSession.getMapper(UsersMapper.class);
    }
    @Test
    public void test01(){

        Users users = mapper.findUsersById2(1);
        System.out.println(users);
    }
    @Test
    public void test02(){
        Users users = mapper.findUserOrder1(1);
        System.out.println(users);
    }
    @Test
    public void test03(){
        mappers = sqlSession.getMapper(OrderMapper.class);
        Order order = mappers.findOrderById2(2);
        System.out.println(order);
    }
    
    @After
    public void after(){
        sqlSession.close();
    }
}

 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>
    <!-- 环境配置 -->
    <!-- 加载类路径下的属性文件 -->
    <properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!-- 数据库连接相关配置 ,db.properties文件中的内容-->
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- mapping文件路径配置 -->
    <mappers>
<!--        全局包扫描-->
        <package name="com.gcx.Mapper"/>
    </mappers>
</configuration>

 数据库文件

use mybatis;
# 创建一个编码表
CREATE TABLE  tb_idcard( 
     id INT PRIMARY KEY AUTO_INCREMENT,
     CODE VARCHAR(18)
);
INSERT INTO tb_idcard(CODE) VALUES('111111111111111');
INSERT INTO tb_idcard(CODE) VALUES('22222222222222');
INSERT INTO tb_idcard(CODE) VALUES('33333333333333');
# 创建一个用户表
create table tb_user(
     uid INT PRIMARY KEY AUTO_INCREMENT,
     uname VARCHAR(32),
     uage INT,
     usex VARCHAR(8),
     ucard_id INT UNIQUE,  
     FOREIGN KEY(ucard_id) REFERENCES tb_idcard(id)
);
insert into tb_user(uname,uage,usex,ucard_id) values('张三',20,'男',2);
insert into tb_user(uname,uage,usex,ucard_id) values('李四',18,'男',3);
insert into tb_user(uname,uage,usex,ucard_id) values('王五',22,'女',1);

# 创建一个订单表表
CREATE TABLE tb_orders (
  or_id int(32) PRIMARY KEY AUTO_INCREMENT,
  order_num varchar(32) NOT NULL,
  user_id int(32) NOT NULL,
  FOREIGN KEY(user_id) REFERENCES tb_user(uid)
);

INSERT INTO tb_orders(order_num,user_id) VALUES('20211111',1);
INSERT INTO tb_orders(order_num,user_id) VALUES('202222222',1);
INSERT INTO tb_orders(order_num,user_id) VALUES('202233333',2);
INSERT INTO tb_orders(order_num,user_id) VALUES('2022444444',3);

#创建一个商品表
CREATE TABLE tb_product (
  pd_id INT(32) PRIMARY KEY AUTO_INCREMENT,
  book_name VARCHAR(32),
  price DOUBLE 
 );
INSERT INTO tb_product(book_name,price) VALUES ('Java基础', '20');
INSERT INTO tb_product(book_name,price) VALUES ('前端技术', '30');
INSERT INTO tb_product(book_name,price) VALUES ('SSM框架', '4');

# 创建一个中间表
CREATE TABLE tb_ordersitem (
    id INT(32) PRIMARY KEY AUTO_INCREMENT,
    or_id INT(32),
    pd_id INT(32),
    FOREIGN KEY(or_id) REFERENCES tb_orders(or_id),
FOREIGN KEY(pd_id) REFERENCES tb_product(pd_id)
);
INSERT INTO tb_ordersitem(or_id,pd_id)  VALUES ('1', '1');
INSERT INTO tb_ordersitem(or_id,pd_id)  VALUES ('1', '3');
INSERT INTO tb_ordersitem(or_id,pd_id)  VALUES ('2', '2');
INSERT INTO tb_ordersitem(or_id,pd_id)  VALUES ('3', '1');
INSERT INTO tb_ordersitem(or_id,pd_id)  VALUES ('3', '2');
INSERT INTO tb_ordersitem(or_id,pd_id)  VALUES ('3', '3');

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_74135466/article/details/127991267

基于mapper代理配置的mybatis多表查询一对一的三种方式-爱代码爱编程

基于Mapper代理配置Mybatis多表查询的一对一映射(三种方式) 一、mybatis多表联查使用内连接 1、两表联查中一对一关系对于POJO的体现(截图忽略了get,set方法)     2、编写对应的PaperMapper接口和在同目录下创建对应sql映射文件PaperMapper.xml 注意: 这里我们在m

基于mapper代理配置的mybatis多表查询一对多-爱代码爱编程

 基于Mapper代理配置的Mybatis多表查询一对多映射 注意: 这里我们在mybatis总配置里设置包扫描 <mappers> <!-- 自动扫描指定包中的sql映射文件 --> <package name="com.ashes.mapper"/> </mappers> 一、使

mybatis 多表联合查询及优化_十一路客的博客-爱代码爱编程_mybatis多表查询优化

参考文章:https://blog.csdn.net/happylee6688/article/details/45967763 对于优化,我这里简单的提几点,大家可以考虑一下。 一. 首先对表的设计,在设计表初期,不仅仅要考虑到数据库的规范性,还好考虑到所谓的业务,以及对性能的影响,比如,如果从规范性角度考虑的话,可能就会分多个表,但是如果从性能角度来考

mybatis框架实现一对多、多对多关系查询,以及递归查询(单表多级分类:省市区三级地址查询)_helloworld!!!的博客-爱代码爱编程

mybatis框架练习 mybatis框架中,包括实体类(这些实体类与数据库中的字段属性相对应),mybatis的配置文件(即mybatis-config.xml,这个配置文件用于连接实体类和orm(object relationship mapping 对象关系映射),以及做连接数据库的配置信息的配置),ORM(相当于xxxDao的实现类,同时将对象和

mybatis学习总结(十)---基于注解的多表查询(一对一,一对多,多对多)_学以致用ht的博客-爱代码爱编程

基于XML的多表联合查询可参考:https://blog.csdn.net/qq_40348465/article/details/84677890    简单介绍所用的一些注解: (1)@Results的基本用法。当数据库字段名与实体类对应的属性名不一致时,可以使用@Results映射来将其对应起来。column为数据库字段名,porperty为实体

mybatis 基于注解开发之多表查询_借汝之光,得以光明的博客-爱代码爱编程

1、多表查询 当我们使用两张或者两张以上的表联合查询时,就会产生四种关系,一对一、一对多、多对一、多对多。前面的文章曾经用xml配置文件的形式讲解了这几种关系。在这里我们将会用注解的方式简述一下如何实现多表联合查询,项目的

mybatis一对多,多对一经典案例及优缺点分析-爱代码爱编程

准备数据 新建俩张表(student表,clalss表)sql语句如下: create table student( sId int primary key auto_increment, sName varchar(20) not null, cId int not null, constraint f_sid_cid foreign key(cId

使用mybatis-plus如何实现零sql做到多表查询-爱代码爱编程

使用mybatis-plus如何实现零sql做到多表查询 在很多时候我们使用mybatis时我们会发现mapper文件写起来太麻烦了,所以现在很多基于mybatis进行封装的框架,这些框架的目的是将一些普通的增删改查帮我们封装好,我们直接继承别人提供的接口就能调用一些基本的增删改查方法了,我们发现在使用的时候这些方法只能实现简单的单表操作,其实框架也支持

springboot中基于Mybatis-Plus多表联查(无xml,通过注解实现)-爱代码爱编程

前言 查阅了mybatis-plus官方文档,发现对多表联查的说明只言片语,也没有例子,只能自己琢磨琢磨如何利用mybatis-plus进行多表联查了。使用xml的方式过于冗余,所以在查看了注解的使用后,果断选择利用注解实现。 注解学习 @Select注解:其实就是在注解后加上相应的sql语句,写法与xml中的一致。@Results注解:有个id属性

mybatis多表联合和嵌套查询-爱代码爱编程

1、Mybatis实现多表联查询方式 业务装配对两个表写单独的sql语句,在业务(service)把查询结果进行联合。使用Auto Mapping特性,在实现两个表联合查询时通过别名完成自动映射。使用Mybatis的<resultMap>标签进行实现2、多表查询时类中包含另一个对象的分类 单个对象集合对象二、resultMap标签 1、写

mybatis-plus实现多表联查-爱代码爱编程

mybatis-plus简介 MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。

mybatis处理多对一映射关系的三种方法_wangqilll的博客-爱代码爱编程

MyBatis使用resultMap自定义映射处理多对一的映射关系的三种方法 1.级联方式处理 2.association标签 3.分步查询 这里是基于t_emp,t_dept员工信息表与部门信息表对应的mapper接口

mybatis多表联查 引出 rdb表关系映射问题-爱代码爱编程

一. 关系型数据库表关系回顾: 1. 一对一: 丈夫表和妻子表是典型的一对一关系;     RDB中的实现方式: 分别创建丈夫表和妻子表, 将对方表主键设为外键, 因为主键的唯一性, 保证了一对一关系; 2. 一对多: 公司和员工一般是一对多关系; (注意: 其实一对多表反过来看是一对一关系, 即一个员工只属于一个公司)     RDB中的实现方式

java-爱代码爱编程

一、动态sql语句 什么是动态sql:根据参数的值,判断sql的条件。 MyBatis 的强大特性之一便是它的动态 SQL,即拼接SQL字符串。如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态 SQL 这一特性可以彻底摆脱这种

java06-爱代码爱编程

前提 总结这个文章的前提是要会基本的SQL语句(我用的MySQL)和JDBC的基本实现。在这个基础上,我们可以通过一些标签或者注解去实现对数据库的多表联查基于一对一和一对多的关系。 第二点,我们在制作数据库时一定要考虑不同的表之间的关系。这种关系指的就是一对一和一对多的关系,举个例子,一个班有许多学生但一个学生不会在不同班上课,因此班级——>学生

mybatis如何实现多表联查_mybatis多表联合查询-爱代码爱编程

一、通过映射配置文件实现多表联查 首先,使用Mysql数据库,创建两个表,分别为学生表Student表和班级表Class表,在Student表中添加列classid参照主表的列id的外键约束。 学生表Student表: 班级表Class表 : 现在去写Dao层和实体类 Student实体类: package com.ape.bean;

mybatis多表查询resultmap设定_mybatis联表查询的resultmap-爱代码爱编程

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 Result Maps 是什么 ResultMap 属性 一、Java数据访问接口 二、XML实现  1、*分步查询 + 延迟加载 三、Test 1.读入数据 总结 Result Maps 是什么    r