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

时间:2017-06-26 04:34:26

标签: java mysql spring-data-jpa jpql

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

Product实体:

@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
}

Brand实体:

@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);
}

但是,如果我为brandName添加新属性Prod并使用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,因为brand_id中没有Product属性,它只是一个列名。那么我怎样才能做到这一点呢?

更新

JPQL查询中出现了一些sytax错误,只需修改如下:

@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类)时,这非常麻烦。那么有一个很好的方法来使用它吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

而不是p.brand_id = b.id,您应该p.brand.id = b.id