13. One to one Association (method 2)

Demand: query all order information, and associated query order user information.

Note: since an order information can only be an order placed by one person, the associated query of user information is one-to-one query starting from the query of order information. If you start from the user information to query the order information, it is one to many query, because a user can place multiple orders.

newsdata one to one tag
tag one to many newsdata/

SELECT
n.nid,
n.title,
t.tid,
t.tname
FROM
newsdata n
LEFT JOIN
tag t ON n.tid=t.tid

Add: LEFT JOIN: display all the tables after from regardless of whether they are related or not
RIGHT JOIN: display all the tables after the RIGHT JOIN, regardless of the Association
//1. Method 1: use resultType
Use resultType to modify the order pojo class, which includes order information and user information
When the object is returned, mybatis automatically injects the user information
 

public class NewsDataTag extends NewsData{
    //Inherits the NewsData class, including all fields of the NewsData class
    //Just fill in other required fields
    private String tid;
    private String tname;
    @Override
    public String toString() {
        return "NewsDataTag [tid=" + tid + ", tname=" + tname + "]";
    }

}

//2.NewsDataMapper

<?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: Namespace, for isolation sql,There is also a very important role, which will be discussed later -->
<mapper namespace="com.xh.mybatis.mapper.NewsDataMapper">
<!-- id:statement Of id Or called sql Of id-->
    <!-- parameterType:Declare the type of input parameter -->
    <!-- resultType:Declare the type of output result, which should be filled in pojo Full path -->
    <!-- #{}: placeholder for input parameter, equivalent to jdbc's? >
    <select id="queryNewsDataTag" resultType="com.xh.mybatis.NewsDataTag">
        SELECT
        n.nid,
        n.title,
        t.tid,
        t.tname
        FROM
        newsdata n
        LEFT JOIN
        tag t ON n.tid=t.tid

    </select>
    
</mapper>

//3. Test method
 

    @Test
    public void test5() {
        // 4. Create SqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<NewsDataTag> list = sqlSession.selectList("queryNewsDataTag");
        System.out.println(list.size());
        // 7. Release resources
        sqlSession.close();
        
    }

Define a special pojo class as the output type, which defines all the fields in the sql query result set. This method is simple and widely used in enterprises.

 

Tags: Mybatis SQL xml encoding

Posted on Thu, 09 Jan 2020 09:53:08 -0800 by cpetercarter