Custom Query for fetching data from multiple table

2020-06-04 09:41发布

问题:

Entities are following

Product Table

@Entity
public class Product implements Serializable {
/*@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;*/

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @NotNull(message = "Product name must not be null")
    @NotEmpty
    private String name;


    @ManyToOne
    @JoinColumn(name="category_id")
    private Category category;

    @ManyToMany(mappedBy = "productlist")
    private List<OrderDetail> orderDetail =new ArrayList<OrderDetail>();

//getters setter

OrderDetail Table

@Entity
public class OrderDetail {

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     private Integer id;


     @ManyToOne
     @JoinColumn(name="purchased_By")
     private user PurchasedBy;


    @ManyToMany
     private Set<Product> productlist = new HashSet<Product>();

These entities generating table named as 'order_detail_productlist' and fields as following order_detail_id and productlist_id

I am running following query in mysql editor and that is working

select u.id, r.name from order_detail u inner join order_detail_productlist ur on(u.id=ur.order_detail_id) inner join product r on(ur.productlist_id=r.id) where u.id="?"

but when i run in spring repository with @Query annotation that is giving me exception. I have tried to change name of Order_detail to OrderDetail according to entities but same exception in both case.

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [select r.name from com.example.Domain.OrderDetail u inner join order_detail_productlist ur on(u.id=ur.order_detail_id) inner join Product r on(ur.productlist_id=r.id) where u.id= :id ]

what i want . i am trying to use in this way .

public final static String product_ordered ="select r.name from OrderDetail u inner join order_detail_productlist ur " +
            "on(u.id=ur.order_detail_id) inner join Product r" +
            " on(ur.productlist_id=r.id)" +
            " where u.id= :id ";

@Query(product_ordered)
public List<Product> findById(@Param("id") int id);

i want to get data from multiple tables , like products that are orderes etc .

回答1:

Your query is not a valid HQL query, which hiberate understands. You can use a native SQL query, but the use case mentioned can be easily achieved with HQL. Before that, lets use the proper annotations mappings for ManytoMany association:

@Entity
@Table(name = "order_detail")
public class OrderDetail {

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     private Integer id;


     @ManyToOne
     @JoinColumn(name="purchased_By")
     private user PurchasedBy;


     @ManyToMany
     @JoinTable(
       name="order_detail_productlist",
       joinColumns=@JoinColumn(name="order_detail_id", referencedColumnName="id"),
       inverseJoinColumns=@JoinColumn(name="productlist_id", referencedColumnName="id"))
      private Set<Product> productlist = new HashSet<Product>();

Product:

@Entity
@Table(name ="product")
public class Product implements Serializable {

      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Integer id;

      @NotNull(message = "Product name must not be null")
      @NotEmpty
      @Column(name = "name", nullable = false)
      private String name;


      @ManyToOne
      @JoinColumn(name="category_id")
      private Category category;

      @ManyToMany(mappedBy = "productlist")
      private List<OrderDetail> orderDetail =new ArrayList<OrderDetail>();

And query :

public final static String product_ordered ="Select p from Product p Join p.orderDetail od Where od.id = :id";

@Query(product_ordered)
public List<Product> findById(@Param("id") int id);

Here is a beginner friendly resource to start with JPA



回答2:

The way you are doing is not possible because you are assigning the result set to List<Product> but the query has some joins, it mean that the result of query is not a Product entity.

You can try to do a Native query. For example:

@PersistenceContext
private EntityManager entityManager;

public List<Object[]> customQuery(int id) {
    Query nativeQuery = entityManager.createNativeQuery(product_ordered).setParameter("id",id);
    return nativeQuery.getResultList();
}