Java自学之mybatis:使用注解方式多对一查询

学习目的:学习使用注解方式实现多对一查询,查询出所有的Product,通过product_中的cid查询到所属的Category。

Part 1

mapper

CategoryMapper

package cn.vaefun.mapper;

import cn.vaefun.pojo.Category;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface CategoryMapper {
    @Insert(" insert into category_ ( name ) values (#{name}) ")
    public int add(Category category);
    @Delete("delete from category_ where id=#{id}")
    public void delete(int id);
    @Select("select * from category_ where id= #{id} ")
    public Category get(int id);
    @Update("update category_ set name=#{name} where id=#{id}")
    public int update(Category category);
    @Select(" select * from category_ ")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "products", javaType = List.class, column = "id", many = @Many(select = "cn.vaefun.mapper.ProductMapper.listByCategory") )
    })
    public List<Category> list();
}

ProductMapper

package cn.vaefun.mapper;

import cn.vaefun.pojo.Product;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface ProductMapper {
    @Select("select * from product_ where cid=#{cid}")
    public List<Product> listByCategory(int cid);
    @Select("select * from product_")
    @Results({
            @Result(property = "category",column = "cid",one = @One(select = 
             "cn.vaefun.mapper.CategoryMapper.get"))
    })
    public List<Product> productList();
}

Part 2

在mybatis-config.xml中配置所需的映射:

<mapper class="cn.vaefun.mapper.CategoryMapper"/>
<mapper class="cn.vaefun.mapper.ProductMapper"/>

Part 3

测试代码块:

    ProductMapper productMapper = session.getMapper(ProductMapper.class);
    ...
    /**
     * 注解方式多对一查询
     * @param productMapper
     */
    private static void listCategoryByProduct(ProductMapper productMapper){
        List<Product> productList = productMapper.productList();
        for (Product p :
                productList) {
            System.out.println(p+"\t对应的分类:\t"+p.getCategory());

        }
    }

测试结果:

v2-b360a08a7be673bdd31f8bca6d15eece_b.jpg

posted @ 2020-03-02 15:27  IMKKA  阅读(4)  评论(0)    收藏  举报  来源