1. 程式人生 > 實用技巧 >mybatis: 一對多通過註解查詢資料

mybatis: 一對多通過註解查詢資料

案例:一對多通過註解查詢資料

1.實體類:

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

 
public class Category {
    private int id;
    private String name;
    List<Product> products;
}

2.dao層:

public interface CategoryMapper {
    
    // 獲取分類資訊和該分類下的所有產品
    @Select(" select * from category_ ")
    @Results({ 
                @Result(property 
= "id", column = "id"),        //property="實體類中的欄位", javaType=結果返回型別 ,column=引數 ,many=@Many("集合查詢介面") @Result(property = "products", javaType = List.class, column = "id", many = @Many(select = "com.mapper.ProductMapper.listByCategory") ) }) public List<Category> list(); }

public interface ProductMapper {
  
    // 根據分類id查詢產品列表
    @Select(" select * from product_ where cid = #{cid}")
    public List<Product> listByCategory(int cid);
     
}