Table of Contents
1. Product order data model
1.1 Data model analysis ideas
1.2 Attribute model analysis
2. One-to-one query
3.1 Requirements
2.2 Method 1: resultType
3.2sql statement
2.2.2 Create pojo
4.4 mapper.xml
4.6mapper.java
2.3. 4.4 Test program
2.3 Method 2: resultMap
2.3.2 The idea of ​​using resultMap mapping
2.3.3 You need to add the user attribute to the orders class
2.3.4.1 Define resultMap
2.3.4.2 Define statement definition
2.4 ResultType and resultMap implement one-to-one query Summary
3. One-to-many query
3.3 Analysis
3.4 Add the list order detail attribute in the Orders class
3.9小结
4.多对多查询
4.1需求
4.2sql语句
4.3映射思路
4.5定义resultMap
4.7测试程序
4.8多对多查询总结
 5.resultMap总结
Home Java javaTutorial Example tutorial of MyBatis related query

Example tutorial of MyBatis related query

Jun 25, 2017 am 10:34 AM
mybatis study build go deep

Please indicate the source for reprinting:

What is coming before: Spring+SpringMVC+MyBatis in-depth learning and construction (5) - dynamic sql

1. Product order data model

1.1 Data model analysis ideas

(1) The data content recorded in each table

The content recorded in each table is divided into modules. Familiarity is equivalent to the process of learning system requirements (functions).

(2) Important field settings for each table

Non-empty fields and foreign key fields

(3)The relationship between database-level tables

Foreign key relationship

(4) Business relationship between tables

When analyzing the business relationship between tables, it must be based on a certain business meaning. Go up and analyze.

1.2 Attribute model analysis

2. One-to-one query

2.1 Requirements

Query order information, association Query order user information.

2.2 Method 1: resultType

2.2.1sql statement

Determine the main table of the query: the order table

Determine the associated table of the query: the user table

Does associated query use internal links? Or an external link?

Since there is a foreign key (user_id) in the orders table, querying the user table through foreign key association can only query one record, and internal links can be used.

SELECT 
  orders.*,  USER.username,  USER.sex,  USER.address 
FROM
  orders,  USER WHERE orders.user_id = user.id
Copy after login

2.2.2 Create pojo

Map the results of the above SQL query to the pojo. The pojo must include all query column names.

The original Orders.java cannot map all fields, and a new pojo needs to be created.

Create a pojo class that inherits more query fields.

2.2.3mapper.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离
    注意:使用mapper代理开发时,namespace有特殊作用,namespace等于mapper接口地址  --><mapper namespace="joanna.yan.mybatis.mapper.OrdersCustomMapper"><!--查询订单,关联查询用户信息  --><select id="findOrdersUser" resultType="joanna.yan.mybatis.entity.OrdersCustom">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address 
        FROM
          orders,
          USER 
        WHERE orders.user_id = user.id</select></mapper>
Copy after login

2.2.4mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息public List<OrdersCustom> findOrdersUser() throws Exception;
}
Copy after login

2.2.5 Test program

  @Testpublic void findOrdersUserTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<OrdersCustom> list=ordersCustomMapper.findOrdersUser();
        System.out.println(list);
        sqlSession.close();
    }
Copy after login

2.3 Method 2: resultMap

2.3.1sql statement

Sql implemented with resultType

2.3.2 The idea of ​​using resultMap mapping

Use resultMap to map the order information in the query results to the Orders object, add the User attribute in the Orders class, and associate the query The user information that comes out is mapped to the user attribute in the orders object.

2.3.3 You need to add the user attribute to the orders class

2.3.4mapper.xml

2.3.4.1 Define resultMap

    <!--订单关联查询用户的resultMap
        将整个查询的结果映射到oanna.yan.mybatis.entity.Orders中      --><resultMap type="joanna.yan.mybatis.entity.Orders" id="OrdersUserResultMap"><!-- 1.配置映射的订单信息  --><!-- id:指定查询列中的唯一标识,订单信息中的唯一标识,如果有多个列组成唯一标识,配置多个id
             column:订单信息中的唯一标识列
             property:订单信息中的唯一标识列所映射到Orders类中的哪个属性          --><id column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><result column="createtime" property="createtime"/><result column="note" property="note"/><!-- 2.配置映射的关联的用户信息  --><!-- association:用于映射关联查询单个对象的信息
             property:要将关联查询的用户信息映射到Orders类中的哪个属性         --><association property="user" javaType="joanna.yan.mybatis.entity.User"><!-- 关联查询用户的唯一标识
                 column:指定唯一标识用户信息的列
                 property:映射到user的哪个属性              --><id column="user_id" property="id"/><result column="username" property="username"/><result column="sex" property="sex"/><result column="address" property="sex"/></association></resultMap>
Copy after login

2.3.4.2 Define statement definition

    <!--查询订单,关联查询用户信息,使用ResultMap  --><select id="findOrdersUserResultMap" resultMap="OrdersUserResultMap">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address 
        FROM
          orders,
          USER 
        WHERE orders.user_id = user.id</select>
Copy after login

2.3.4.3mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息,使用resultMappublic List<Orders> findOrdersUserResultMap() throws Exception;
}
Copy after login

2.3. 4.4 Test program

    @Testpublic void findOrdersUserResultMapTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<Orders> list=ordersCustomMapper.findOrdersUserResultMap();
        System.out.println(list);
        sqlSession.close();
    }
Copy after login

2.4 ResultType and resultMap implement one-to-one query Summary

Realize one-to-one query:

resultType: Use resultType to achieve more Simple, if the pojo does not include the queried column name, you need to add the attribute corresponding to the column name to complete the mapping.

If there are no special requirements for query results, it is recommended to use resultType.

resultMap: You need to define resultMap separately, which is a bit troublesome to implement. If you have special requirements for the query results, you can use resultMap to map the associated query to the attributes of the pojo.

resultMap can implement delayed loading, but resultType cannot implement delayed loading.

3. One-to-many query

3.1 Requirements

Query order and order details information

3.2sql statement

Determine the master Query table: Order table

Determine the association Query table: Order details table

Just add the order details table association based on one-to-one query.

SELECT 
  orders.*,  USER.username,  USER.sex,  USER.address,
  orderdetail.id orderdetail_id,
  orderdetail.items_id,
  orderdetail.items_num,
  orderdetail.orders_idFROM
  orders,  USER,
  orderdetailWHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id
Copy after login

3.3 Analysis

Use resultType to map the above query results to pojo, and the order information will be repeated.

Requirements:

The mapping of orders cannot have duplicate records.

Solution:

Add the List orderDetails attribute in the Orders.java class.

The order information will eventually be mapped to Orders, and the order details corresponding to the order will be mapped to the orderDetails attribute in orders.

The number of mapped orders records is two (orders information is not repeated)

The orderDetails attribute in each order stores the order details corresponding to the order.

3.4 Add the list order detail attribute in the Orders class

##3.5 Define resultMap

    <!--订单及订单明细的resultMap
        使用extends继承,就不需要再配置订单信息和用户信息的映射了      --><resultMap type="joanna.yan.mybatis.entity.Orders" id="OrdersAndOrderDetailResultMap" extends="OrdersUserResultMap"><!-- 1.配置映射的订单信息  --><!-- 2.配置映射的关联的用户信息  --><!-- 使用extends继承,就不需要再配置订单信息和用户信息的映射了 --><!-- 3.配置映射的订单明细信息  --><!-- 订单明细信息
             一个订单关联查询出了多条明细,要使用collection进行映射
             collection:对关联查询到的多条记录映射到集合对象中
             property:将关联查询到多条记录映射到joanna.yan.mybatis.entity.Orders中的哪个属性
              ofType:指定映射到list集合属性中pojo的类型         --><collection property="orderdetails" ofType="joanna.yan.mybatis.entity.Orderdetail"><!-- id:订单明细的唯一标识
                 property:要讲订单明细的唯一标识映射到joanna.yan.mybatis.entity.Orderdetail的哪个属性              --><id column="orderdetail_id" property="id"/><result column="items_id" property="itemsId"/><result column="items_num" property="itemsNum"/><result column="orders_id" property="ordersId"/></collection></resultMap>
Copy after login
3.6mapper. xml

    <!-- 查询订单,关联查询用户及订单明细,使用resultMap --><select id="findOrdersAndOrderDetailResultMap" resultMap="OrdersAndOrderDetailResultMap">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address,
          orderdetail.id orderdetail_id,
          orderdetail.items_id,
          orderdetail.items_num,
          orderdetail.orders_id
        FROM
          orders,
          USER,
          orderdetail
        WHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id</select>
Copy after login
3.7mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息public List<OrdersCustom> findOrdersUser() throws Exception;//查询订单,关联查询用户信息,使用resultMappublic List<Orders> findOrdersUserResultMap() throws Exception;//查询订单(关联用户)及订单明细public List<Orders> findOrdersAndOrderDetailResultMap() throws Exception;
}
Copy after login
3.8 Test program

    @Testpublic void findOrdersAndOrderDetailResultMapTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<Orders> list=ordersCustomMapper.findOrdersAndOrderDetailResultMap();
        System.out.println(list);
        sqlSession.close();
    }
Copy after login

3.9小结

mybatis使用resultMap的collection对关联查询的多条记录映射到有个list集合属性中。

使用resultType实现:

将订单明细映射到orders中的orderdetails中,需要自己处理,使用双重循环遍历,去掉重复记录,将订单明细放在ordertails中。

4.多对多查询

4.1需求

查询用户及用户购买的商品信息。

4.2sql语句

查询主表:用户表

关联表:由于用户和商品没有直接关联,通过订单和订单明细进行关联,所有关联表:orders、orderdetail、items。

SELECT 
  orders.*,  USER.username,  USER.sex,  USER.address,
  orderdetail.id orderdetail_id,
  orderdetail.items_id,
  orderdetail.items_num,
  orderdetail.orders_id,
  items.name items_name,
  items.detail items_detail,
  items.price items_priceFROM
  orders,  USER,
  orderdetail,
  itemsWHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id AND orderdetail.items_id = items.id
Copy after login

4.3映射思路

将用户信息映射到user中。

在User类中添加订单列表属性List orderslist,将用户创建的订单映射到orderslist;

在Orders中田间订单明细列表属性List orderdetails,将订单的明细映射到orderdetails;

在OrderDetail中添加Items属性,将订单明细所对应的商品映射到Items。

4.4 mapper.xml

    <select id="findUserAndItemsResultMap" resultMap="UserAndItemsResultMap">SELECT 
          orders.*,
          USER.username,
          USER.sex,
          USER.address,
          orderdetail.id orderdetail_id,
          orderdetail.items_id,
          orderdetail.items_num,
          orderdetail.orders_id,
          items.name items_name,
          items.detail items_detail,
          items.price items_price
        FROM
          orders,
          USER,
          orderdetail,
          items
        WHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id AND orderdetail.items_id = items.id        </select>
Copy after login

4.5定义resultMap

    <!-- 查询用户及购买商品  --><resultMap type="joanna.yan.mybatis.entity.User" id="UserAndItemsResultMap"><!-- 1.用户信息 --><id column="user_id" property="id"/><result column="username" property="username"/><result column="sex" property="sex"/><result column="address" property="address"/><!-- 2.订单信息 --><!-- 一个用户对应多个订单,使用collection映射 --><collection property="ordersList" ofType="joanna.yan.mybatis.entity.Orders"><id column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><result column="createtime" property="createtime"/><result column="note" property="note"/><!-- 3.订单明细  --><!-- 一个订单包括多个明细 --><collection property="orderdetails" ofType="joanna.yan.mybatis.entity.Orderdetail"><id column="orderdetail_id" property="id"/><result column="items_id" property="itemsId"/><result column="items_num" property="itemsNum"/><result column="orders_id" property="ordersId"/><!-- 4.商品信息  --><!-- 一个订单明细对应一个商品 --><association property="items" javaType="joanna.yan.mybatis.entity.Items"><id column="items_id" property="id"/><result column="items_name" property="name"/><result column="items_detail" property="detail"/><result column="items_price" property="price"/></association></collection></collection></resultMap>
Copy after login

4.6mapper.java

public interface OrdersCustomMapper {//查询订单,关联查询用户信息public List<OrdersCustom> findOrdersUser() throws Exception;//查询订单,关联查询用户信息,使用resultMappublic List<Orders> findOrdersUserResultMap() throws Exception;//查询订单(关联用户)及订单明细public List<Orders> findOrdersAndOrderDetailResultMap() throws Exception;//查询用户购买商品信息public List<User> findUserAndItemsResultMap() throws Exception;
}
Copy after login

4.7测试程序

    @Testpublic void findUserAndItemsResultMapTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<User> list=ordersCustomMapper.findUserAndItemsResultMap();
        System.out.println(list);
        sqlSession.close();
    }
Copy after login

4.8多对多查询总结

将查询用户购买的商品信息明细清单(用户名、用户地址、购买商品名称、购买商品时间、购买商品数量)

针对上面的需求就使用resultType将查询到的记录映射到一个扩展的pojo中,很简单实现明细清单的功能。

一对多是多对多的特例,如下需求:

查询用户购买的商品信息,用户和商品的关系是多对多关系。

需求1:

查询字段:用户账号、用户名称、用户性别、商品名称、商品价格(最常见)

企业开发中常见明细列表,用户购买商品明细列表,

使用resultType将上边查询列映射到pojo输出。

需求2:

查询字段:用户账号、用户名称、购买商品数量、商品明细(鼠标移上显示明细)

使用resultMap将用户购买的商品明细列表映射到user对象中。

总结:

使用resultMap是针对那些对查询结果映射有特殊要求的功能,比如特殊要求映射成list中包含多个list。

 5.resultMap总结

resultType:

作用:将查询结果按照sql列名pojo属性一致性映射到pojo中。

场合:

  常见一些明细记录的展示,比如用户购买商品明细,将关联查询信息全部展示在页面时,此时可直接使用resultType将每一条记录映射到pojo中,在前端页面遍历list(list中是pojo)即可。

resultMap:

  使用association和collection完成一对一和一对多高级映射(对结果又特殊的映射要求)。

association:

作用:将关联查询信息映射到一个pojo对象中。

场合:

为了方便查询关联信息可以使用association将关联订单信息映射为用户对象的pojo属性中,比如:查询订单及关联用户信息。

  使用resultType无法将查询结果映射到pojo对象的pojo属性中,根据对结果集查询遍历的需要选择使用resultType还是resultMap。

collection:

作用:将关联查询信息映射到一个list集合中。

场合:为了方便擦还行遍历关联信息可以使用collection将关联信息映射到list集合中,比如:查询用户权限范围模块及模块下的菜单,可使用collection将模块映射到模块list中,将菜单列表映射到模块对象的菜单list属性中,这样做册目的也是方便对查询结果集进行遍历查询。

  如果使用resultType无法将查询结果映射到list集合中。 

The above is the detailed content of Example tutorial of MyBatis related query. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Revealing the appeal of C language: Uncovering the potential of programmers Revealing the appeal of C language: Uncovering the potential of programmers Feb 24, 2024 pm 11:21 PM

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Feb 25, 2024 pm 12:30 PM

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

Let's learn how to input the root number in Word together Let's learn how to input the root number in Word together Mar 19, 2024 pm 08:52 PM

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

Can buildings be built in the wild in Mistlock Kingdom? Can buildings be built in the wild in Mistlock Kingdom? Mar 07, 2024 pm 08:28 PM

Players can collect different materials to build buildings when playing in the Mistlock Kingdom. Many players want to know whether to build buildings in the wild. Buildings cannot be built in the wild in the Mistlock Kingdom. They must be within the scope of the altar. . Can buildings be built in the wild in Mistlock Kingdom? Answer: No. 1. Buildings cannot be built in the wild areas of the Mist Lock Kingdom. 2. The building must be built within the scope of the altar. 3. Players can place the Spirit Fire Altar by themselves, but once they leave the range, they will not be able to construct buildings. 4. We can also directly dig a hole in the mountain as our home, so we don’t need to consume building materials. 5. There is a comfort mechanism in the buildings built by players themselves, that is to say, the better the interior, the higher the comfort. 6. High comfort will bring attribute bonuses to players, such as

Learn the main function in Go language from scratch Learn the main function in Go language from scratch Mar 27, 2024 pm 05:03 PM

Title: Learn the main function in Go language from scratch. As a simple and efficient programming language, Go language is favored by developers. In the Go language, the main function is an entry function, and every Go program must contain the main function as the entry point of the program. This article will introduce how to learn the main function in Go language from scratch and provide specific code examples. 1. First, we need to install the Go language development environment. You can go to the official website (https://golang.org

Real-time monitoring of SQL output in the MyBatis console Real-time monitoring of SQL output in the MyBatis console Feb 25, 2024 pm 03:48 PM

MyBatis is a popular persistence layer framework that provides convenient SQL mapping and database operation functions, allowing developers to interact with the database more efficiently. In the actual development process, we sometimes need to print out the SQL statements executed by MyBatis on the console in real time to better debug and optimize SQL queries. This article will introduce how to realize real-time printing of SQL on the console in MyBatis and provide specific code examples. First, we need to add My

Quickly install PyTorch in PyCharm: an easy guide Quickly install PyTorch in PyCharm: an easy guide Feb 24, 2024 pm 09:54 PM

PyTorch Installation Guide: Quickly set up a development environment in PyCharm PyTorch is one of the most popular frameworks in the current field of deep learning. It has the characteristics of ease of use and flexibility, and is favored by developers. This article will introduce how to quickly set up the PyTorch development environment in PyCharm, so that you can start the development of deep learning projects. Step 1: Install PyTorch First, we need to install PyTorch. The installation of PyTorch usually needs to take into account the system environment

See all articles