java - 在 Spring Data Jpa 中使用 JPQL 加入查询

标签 java mysql spring-data-jpa jpql

我在 spring data jpa 中使用 JPQL 创建了一个 left join 查询,但在我的单元测试中失败了。项目中有两个实体。

产品实体:

@Entity
@Table(name = "t_goods")
public class Product implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "id", length = 6, nullable = false)
    private Integer id;
    @Column(name = "name", length = 20, nullable = false)
    private String name;
    @Column(name = "description")
    private String desc;
    @Column(name = "category", length = 20, nullable = false)
    private String category;
    @Column(name = "price", nullable = false)
    private double price;
    @Column(name = "is_onSale", nullable = false)
    private Integer onSale;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "brand_id")
    private Brand brand;
    // getter and setter
}

品牌实体:

@Entity
@Table(name = "tdb_goods_brand")
public class Brand implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "id", length = 6, nullable = false)
    private  Integer id;
    @Column(name = "brand_name", unique = true, nullable = false)
    private String name;

    @OneToMany(mappedBy = "brand", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Product> products;
    // getter and setter
}

第三个类 Prod 将查询结果映射到 Object:

public class Prod implements Serializable {
    private Integer id;
    private String name;
    private double price;
    //private String brandName;
    // getter and setter
}

它可以很好地处理这个查询:

public interface ProductRepository extends JpaRepository<Product, Integer> {
    @Query(value = "select new com.pechen.domain.Prod(p.id, p.name, p.price) from Product p ")
    Page<Prod> pageForProd(Pageable pageRequest);
}

但是如果我为 Prod 添加新属性 brandName 并使用 left join 重构查询,它测试失败:

@Query(value = "select new com.pechen.domain.Prod(p.id, p.name, p.price, b.name) from Product p left join com.pechen.domain.Brand b on p.brand_id = b.id")
Page<Prod> pageForProd(Pageable pageRequest);

问题似乎出在 on p.brand_id = b.id 上,因为 Product 中没有 brand_id 属性,它只是列名。那么我怎样才能让它发挥作用呢?

更新:

JPQL 查询中出现了一些语法错误,只需按以下方式修复即可:

@Query(value = "select new com.pechen.domain.Prod(p.id, p.name, p.price, b.name) from Product p left join p.brand b")
Page<Prod> pageForProd(Pageable pageRequest);

此外,这种方式每次都创建另一个类来将查询结果映射到对象(我指的是Prod类),非常麻烦。那么有没有好的方法来处理它呢?任何帮助将不胜感激。

最佳答案

而不是 p.brand_id = b.id 你应该做 p.brand.id = b.id

关于java - 在 Spring Data Jpa 中使用 JPQL 加入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44753171/

相关文章:

java - 使用switch语句返回不同的页面实例

java - 以 XML 格式发送 blob 或字节数组

c# 遇到 mysql : Incorrect string value code 1366 for column at row 1 问题

php - 如何在不丢失数据的情况下更新整个数据库

spring-data-jpa - Spring data mongoDb 不是像 Spring data Jpa 这样的 null 注释

Java,是否可以在不创建临时文件的情况下用字符串替换文件的第N行?

java - 我怎样才能让GSON解析JSON字符串

mysql - 如何从表中删除除一条记录之外的所有重复记录?

spring - 使用带有 Spring Data 和绑定(bind)参数的 Postgres JSONB 查询失败并出现 InvalidDataAccessApiUsageException

java - 测试使用其他测试的内部 ContextConfiguration