Multi-table joint query based on MyBatis (one-to-many-to-many-to-many)

Table of contents

hierarchical structure

Mapper interface

IdCardMapper

 OrderMapper

ProductMapper

UsersMapper

 pojo entity class

IdCard

Order

 Product

 Tools:

MybatisUtil

 Mapping file ***Mapper.xml

IdCardMapper

OrderMapper

 ProductMapper

UsersMapper

 Test test

 mybatis-config.xml

 database file


hierarchical structure

 

 In the java layer, the resources layer and the test test suggest that the hierarchical structure is the same

The target generated in this way looks clear at a glance!

Mapper interface

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 entity class

// Because the lombok dependency is introduced here , the Data annotation written directly for simplicity ( not recommended )

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;

}

 Tools:

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);
    }
}

 Mapping file ***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 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>

 database file

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');

 

Guess you like

Origin blog.csdn.net/m0_74135466/article/details/127991267