300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > springboot jpa自定义SQL查询

springboot jpa自定义SQL查询

时间:2019-11-04 21:55:28

相关推荐

springboot jpa自定义SQL查询

说明

在使用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();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。