分类和产品的一对多关系
一个分类中有多个产品
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 + "]"; } }
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 + "]"; } }
Category.xml:
通过left join关联查询,对Category和Product表进行关联查询。 这里不是用的resultType, 而是resultMap,通过resultMap把数据取出来放在对应的 对象属性里 注: Category的id 字段 和Product的id字段同名,Mybatis不知道谁是谁的,所以需要通过取别名cid,pid来区分。 name字段同理。 <?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="Category" id="categoryBean"> <id column="cid" property="id" /> <result column="cname" property="name" /> <!-- 一对多的关系 --> <!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 --> <collection property="products" ofType="Product"> <id column="pid" property="id" /> <result column="pname" property="name" /> <result column="price" property="price" /> </collection> </resultMap> <!-- 关联查询分类和产品表 --> <select id="listCategory" resultMap="categoryBean"> 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>