Java自学之mybatis:使用注解实现一对多查询

学习目的:在xml方式实现一对多查询的基础上,使用注解实现一对多查询。

Part 1

新建一个ProductMapper:

package cn.vaefun.mapper;

import cn.vaefun.pojo.Product;
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);
}

Part 2

新建一个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();
}

@Select注解获取Category类本身。
@Results 通过@Result和@Many中调用ProductMapper.listByCategory()方法相结合,来获取一对多关系。

Part 3

测试代码块:

    /**
     * 注解方式一对多查询
     * @param mapper
     */
    private static void listProductByCategory(CategoryMapper mapper){
        List<Category> categoryList = mapper.list();
        for (Category c :
                categoryList) {
            System.out.println(c.getName());
            List<Product> productList = c.getProducts();
            for (Product p :
                    productList) {
                System.out.println(p);
            }
        }
    }

测试结果:

v2-6ebec76ff73cf0710c2c243bfbcd1693_b.jpg

posted @ 2020-03-02 14:49  IMKKA  阅读(17)  评论(0)    收藏  举报  来源