Mybatis Series Textbook - Basic - many to one

Step 1: run first, see the effect, and then learn
Step 2: imitation and troubleshooting
Step 3: many to one relationship
Step 4: see the effect before learning
Step 5: modify product java
Step 6: product xml
Step 7: mybatis config xml
Step 8: Test mybatis
Step 9: runnable projects
Step 10: Exercise - modify the many to one relationship
Step 11: answer - modify the many to one relationship

Step 1: run first, see the effect, and then learn

Old rule, download first Download area (click to enter) After the runnable project is configured and run, and it is confirmed that it is available, we can learn what steps have been taken to achieve this effect.

Step 2: imitation and troubleshooting

After ensuring that the runnable project can run correctly, follow the steps of the tutorial strictly and imitate the code again.
It is inevitable that there are code differences in the imitation process, resulting in the failure to get the expected running results. At this moment, locate the problem by comparing the correct answer (runnable project) with your own code.
In this way, learning is effective and error elimination is efficient, which can significantly improve the learning speed and cross all barriers on the learning road.

diffmerge software is recommended for folder comparison. Compare your own project folder with my runnable project folder.
This software is very awesome. You can know which two files in the folder are wrong and mark them clearly
Here is a green installation and use tutorial: diffmerge download and use tutorial

Step 3: many to one relationship

This knowledge point is based on One to many Explain the many to one relationship on the basis of

Step 4: see the effect before learning

This is a many to one query effect. All products can be queried. At the same time, the corresponding classification of each product can be seen

Step 5: modify product java

Add category attribute to Product

package com.how2java.pojo;

public class Product {
    private int id;
    private String name;
    private float price;
    private Category category;

    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
    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 float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
    }

}

Step 6: product xml

Provide product XML and configure the sql statement of associated query through listProduct.
Then, the fields and attributes are mapped through resultMap.
Use association for many to one relationship association, and specify the one-to-one correspondence between the table field name and the object attribute name
Note: the id field of Category has the same name as the id field of Product. Mybatis doesn't know who belongs to whom, so it needs to be distinguished by taking the aliases CID and PID.
The same is true for the name field.

<?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">
<mapper namespace="com.how2java.pojo">
    <resultMap type="Product" id="productBean">
        <id column="pid" property="id" />
        <result column="pname" property="name" />
        <result column="price" property="price" />

        <!-- Many to one relationship -->
        <!-- property: Refers to the attribute name, javaType: Refers to the type of property -->
        <association property="category" javaType="Category">
            <id column="cid" property="id"/>
            <result column="cname" property="name"/>
        </association>
    </resultMap>

    <!-- according to id query Product, Association will Orders Find out -->
    <select id="listProduct" resultMap="productBean">
            select c.*, p.*, c.id 'cid', p.id 'pid', c.name 'cname', p.name 'pname' from category_ c left join product_ p on c.id = p.cid
        </select>
</mapper>

Step 7: mybatis config xml

In mybatis config XML for product XML Mapping

<?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>
    <typeAliases>
        <package name="com.how2java.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/how2java/pojo/Category.xml"/>
        <mapper resource="com/how2java/pojo/Product.xml"/>
    </mappers>
</configuration>

Step 8: Test mybatis

package com.how2java;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 com.how2java.pojo.Product;

public class TestMybatis {

    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();

        List<Product> ps = session.selectList("listProduct");
        for (Product p : ps) {
            System.out.println(p+" The corresponding classification is \t "+ p.getCategory());
        }
        session.commit();
        session.close();
    }
}

Step 9: runnable projects

stay Download area (click to enter) Download the runnable items corresponding to this knowledge point

For more information, click to learn: https://how2j.cn/k/mybatis/mybatis-many-to-one/1090.html

Tags: Java Mybatis Back-end

Posted by M. Abdel-Ghani on Tue, 24 May 2022 13:15:21 +0300