【发布时间】:2019-08-08 07:39:33
【问题描述】:
我有一个使用 PostgreSQL RDBMS 的 spring boot 项目。 我在两个实体(客户和产品)之间有 @ManyToMany 关系。他们由 customer_product 加入。但是在存储库层形成 JPQL 时,我遇到了困难。这是实体:
@Entity
@NamedQuery(name="Customer.findAll", query="SELECT c FROM Customer c")
public class Customer implements Serializable {
... all properties ... getter setter constructor...
//bi-directional many-to-many association to Product
@JsonIgnore
@ManyToMany
@JoinTable(
name="customer_product"
, joinColumns={
@JoinColumn(name="customer_id")
}
, inverseJoinColumns={
@JoinColumn(name="product_id")
}
)
private List<Product> products;
@Entity
@NamedQuery(name="Product.findAll", query="SELECT p FROM Product p")
public class Product implements Serializable {
... all properties ... getter setter ... constructors ...
//bi-directional many-to-many association to Customer
@JsonIgnore
@ManyToMany(mappedBy="products")
private List<Customer> customers;
稍后在存储库中:
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
//Below mentioned query works perfectly as Customer & Address has OneToMany Relation
@Query("select new com.arindam.springjpa.springdatajpaexamples.vo.CustomerDetailsVO(c.id, c.customerName, a.fullAddress) from Customer c, Address a where c.address.addressId=a.addressId")
List<CustomerDetailsVO> findAllCustomerDetails();
// But I need help on below query
// I want to find out full details of ManyToMany relation between customer & product
@Query("select new com.arindam.springjpa.springdatajpaexamples.vo.CustomerProductAddressDetailsVO(c.id, c.customerName, a.fullAddress, p.productName) from Customer c, Address a, Product p where c.address.addressId=a.addressId and c.products.product.productId=p.productId")
List<CustomerProductAddressDetailsVO> findAllCustomerAddressProductDetails();
这里的VO有结果是简单的VO类
@Entity
public class CustomerProductAddressDetailsVO {
private Integer id;
private String customerName;
private String fullAddress;
private String productName;
//Like a simple POJO with getter setter constructors
你能推荐一下吗?
感谢您的宝贵反馈。
【问题讨论】:
-
您需要使用连接(即使对于您的第一个查询)。见docs.jboss.org/hibernate/orm/current/userguide/html_single/…。第一个查询实际上应该看起来像
select new ... from Customer c join c.address。我会让你阅读文档并找出第二个应该是什么。 -
@JB Nizet - 非常感谢。第一个查询完美运行。但是第二个有问题。第二个查询是多对多,因此是两个列表。所以无法加入。
-
您尝试了哪些查询,结果如何?
标签: java spring-boot spring-data-jpa jpql