Spring Data JPA - ManyToMany - JPQL - формирование @Query в репозитории - PullRequest
0 голосов
/ 18 марта 2019

У меня есть проект весенней загрузки с СУБД PostgreSQL.У меня есть @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

Можете ли вы предложить.

Спасибо за ваш ценный отзыв.

1 Ответ

0 голосов
/ 18 марта 2019

Я решил проблему. Поскольку классы сущностей были сгенерированы с помощью плагинов Eclipse, класс для customer_product не был создан. Поэтому я вручную сгенерировал его и использовал запрос. Итоговый код:

@Entity
@Table(name="customer_product")
@NamedQuery(name="CustomerProduct.findAll", query="SELECT c FROM CustomerProduct c")
public class CustomerProduct implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private Integer id;

    @Column(name="customer_id")
    private Integer customerId;

    @Column(name="product_id")
    private Integer productId;

и слой репозитория:

@Query("select new com.arindam.springjpa.springdatajpaexamples.vo.CustomerProductAddressDetailsVO(cp.id, c.customerName, a.fullAddress, p.productName) from Customer c, Address a, Product p, CustomerProduct cp "
            + "where c.address.addressId=a.addressId and cp.productId=p.productId and cp.customerId=c.id")
    List<CustomerProductAddressDetailsVO> findAllCustomerAddressProductDetails();

Работает отлично.

...