【发布时间】:2017-11-28 21:46:20
【问题描述】:
我在 spring data jpa 中使用JPQL 创建了一个left join 查询,但在我的单元测试中失败了。项目中有两个实体。
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);
}
但如果我为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类)非常麻烦。那么有没有好的方法来使用它呢?任何帮助将不胜感激。
【问题讨论】:
标签: java mysql spring-data-jpa jpql