说明
在使用JPA实现数据持久化过程中经常会遇到这种情况:我有2张表是一对多的关系,需要通过一个外键ID去关联查询到另外一张表的字段。例如,1张商品表food_info
其中存有商品分类IDcategory_id
关联商品分类表food_category
,那么我需要在查询商品的时候同时查出存储在商品分类表中的分类名称列category_name
。
要达到的效果
在页面列表中展示查询到的商品分类中文名。
实现代码
这里主要借助JPA提供的@Query
自定义查询语句。在查询之前需要先定义几个模型类。
商品表模型
@Data@Entitypublic class FoodInfo {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;private String foodName;private BigDecimal price;private String icon; // 商品图片private String info; // 商品描述private Integer stock; // 商品库存private Integer categoryId; // 商品分类private Date createTime;private Date updateTime;}
商品分类表模型
@Data@Entitypublic class FoodCategory {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;private String categoryCode; // 分类编码private String categoryName; // 分类名称private Date createTime;private Date updateTime;}
商品VO模型
@Data@AllArgsConstructorpublic class FoodVO {private Integer id;private String foodName;private BigDecimal price;private String icon; // 商品图片private String info; // 商品描述private Integer stock; // 商品库存private Integer categoryId; // 商品分类private String categoryName; // 商品名称}
商品Repository
@Query("SELECT new com.test.food_mall.vo.FoodVO(f.id, f.foodName,f.price,f.icon,f.info,f.stock,f.categoryId,c.categoryName) " +"from FoodInfo f left join FoodCategory c " +"on f.categoryId = c.id")List<FoodVO> findAllCustom();