springboot jpa自定义SQL查询

说明

在使用JPA实现数据持久化过程中经常会遇到这种情况:我有2张表是一对多的关系,需要通过一个外键ID去关联查询到另外一张表的字段。例如,1张商品表food_info其中存有商品分类ID category_id关联商品分类表food_category,那么我需要在查询商品的时候同时查出存储在商品分类表中的分类名称列category_name

要达到的效果

在页面列表中展示查询到的商品分类中文名。
在这里插入图片描述

实现代码

这里主要借助JPA提供的@Query自定义查询语句。在查询之前需要先定义几个模型类。

商品表模型

@Data
@Entity
public 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
@Entity
public class FoodCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String categoryCode; // 分类编码
    private String categoryName; // 分类名称
    private Date createTime;
    private Date updateTime;
}

商品VO模型

@Data
@AllArgsConstructor
public 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();
posted @   一锤子技术员  阅读(82)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示