首页 > 其他 > 详细

MyBatis之一对多查询

时间:2020-10-23 00:02:15      阅读:49      评论:0      收藏:0      [点我收藏+]

MyBatis之一对多查询

接续上一节:MyBatis之模糊查询和多条件查询。

本节的目标是利用Category和Product实现一对多查询,查出来的一个Category下包含多个Product。

添加新的实体类

新增Product实体类

package com.nyf.pojo;
 
public class Product {
    private int id;
    private String name;
    private float price;
    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 + "]";
    }
 
}

修改Category类,添加一个元素类型为Product类型的List,代表一个Category可以包含多个Product,并添加Get和Set方法,如下所示:

package com.nyf.pojo;

import java.util.List;

public class Category {
    private int id;
    private String name;
    List<Product> products;
    
    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 List<Product> getProducts() {
        return products;
    }
    public void setProducts(List<Product> products) {
        this.products = products;
    }
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
     
}

配置新方法

为了方便,配置新方法前还需要在mybatis-config.xml文件中声明Product类的别名,只需要仿照Category添加在typeAliases标签内就可以了。目前还是查询Category,不需要为Product添加查询方法,所以暂时不需要建立Product.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>
    <!-- typeAliases用来给com.nyf.pojo.Category取别名为Category -->
    <typeAliases>
      <typeAlias alias="Category" type="com.nyf.pojo.Category" />
      <typeAlias alias="Product" type="com.nyf.pojo.Product" />
    </typeAliases>
    
    <!-- environments配置要连接的数据库 -->
    <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/nyf?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    <!-- mappers,指明实体类对应的配置文件 -->
    <mappers>
        <mapper resource="com/nyf/config/Category.xml"/>
    </mappers>
</configuration>

修改Category.xml添加一个名为listCategory_oneToMany的方法, 还有一个resultMap。

<?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.nyf.config">
        <!-- listCategory方法(select操作),id相当于方法名,resultType代表返回集合中的元素类型-->
        <select id="listCategory" resultType="Category">
            select * from   category_     
        </select>
        
        <!-- addCategory方法(insert操作),parameterType代表入参类型,name是Category的一个属性,用#取属性值-->
        <insert id="addCategory" parameterType="Category" >
            insert into category_ ( name ) values (#{name})   
        </insert>
        
        <!-- deleteCategory方法(delete操作) -->
        <delete id="deleteCategory" parameterType="Category" >
            delete from category_ where id= #{id}  
        </delete>
         
        <!-- getCategory方法(select操作),_int代表入参是int类型 -->
        <select id="getCategory" parameterType="_int" resultType="Category">
            select * from   category_  where id= #{id}   
        </select>
 
 		<!-- updateCategory方法(update操作) -->
        <update id="updateCategory" parameterType="Category" >
            update category_ set name=#{name} where id=#{id}   
        </update>
        
        <!-- listCategoryByName方法,其中#{0}取第一个,在此处也是唯一一个字符串 -->
        <select id="listCategoryByName"  parameterType="string" resultType="Category">
            select * from   category_  where name like concat(‘%‘,#{0},‘%‘)
        </select>
        
        <!-- listCategoryByIdAndName方法,入参类型是map,可根据id和name这两个key进行取值 -->
        <select id="listCategoryByIdAndName"  parameterType="map" resultType="Category">
            select * from   category_  where id= #{id}  and name like concat(‘%‘,#{name},‘%‘)
        </select>  
        
        <!-- type="Category"代表resultMap最后生成的还是Category类型对象 -->
        <resultMap type="Category" id="categoryBean">
            <id column="cid" property="id" />
            <result column="cname" property="name" />
     
            <!-- 一对多的关系 -->
            <!-- property: 指的是pojo中的属性名, ofType:指的是collection集合中元素的类型, id表明主键,result指一般字段,column指的是SQL结果中的一般列名-->
            <collection property="products" ofType="Product">
                <id column="pid" property="id" />
                <result column="pname" property="name" />
                <result column="price" property="price" />
            </collection>
        </resultMap>
     
        <!-- 关联查询分类和产品表, resultMap="categoryBean" 会把查询结果映射填充成一个categoryBean-->
        <select id="listCategory_oneToMany" resultMap="categoryBean">
            select 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>

编写测试类

package com.nyf.tests;

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.nyf.pojo.Category;
import com.nyf.pojo.Product;

public class OneToMany {
public static void main(String[] args) throws IOException {
    	
    	//读取com.nyf.config包内mybatis-config.xml文件
        String resource = "com/nyf/config/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        
        //获取session
        SqlSessionFactory sqlSessionFactory = new 			               SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=sqlSessionFactory.openSession();
        //调用listCategory_oneToMany方法
        List<Category> cs = session.selectList("listCategory_oneToMany");
        for (Category c : cs) {
            System.out.println(c);
            List<Product> ps = c.getProducts();
            for (Product p : ps) {
                System.out.println("\t"+p);
            }
        }
        
        //提交事务???
        session.commit();
        //session关闭
        session.close();
    }
}

结果验证

正确结果应该如下所示:

Category [id=1, name=category1]
	Product [id=1, name=product a, price=0.0]
	Product [id=2, name=product b, price=0.0]
	Product [id=3, name=product c, price=0.0]
Category [id=2, name=category2]
	Product [id=4, name=product x, price=0.0]
	Product [id=5, name=product y, price=0.0]
	Product [id=6, name=product z, price=0.0]

MyBatis之一对多查询

原文:https://www.cnblogs.com/nyfblog/p/13861606.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!