我在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
类)时,这非常麻烦。那么有一个很好的方法来使用它吗?任何帮助将不胜感激。
答案 0 :(得分:3)
而不是p.brand_id = b.id
,您应该p.brand.id = b.id