2017-06-26 73 views
0

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

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映射查询结果对象:

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增加新属性brandNameleft 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查询的一些语法时才错误,只是修复它,如下所示:

@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类)。那么有没有一种好的方法来处理它?任何帮助,将不胜感激。

回答

3

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