Custom Query for fetching data from multiple tables in spring Data Jpa

前端 未结 2 762
梦毁少年i
梦毁少年i 2021-02-10 00:49

Entities are following

Product Table

@Entity
public class Product implements Serializable {
/*@Id
@GeneratedValue(strategy = Generation         


        
2条回答
  •  无人共我
    2021-02-10 01:06

    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 productlist = new HashSet();
    

    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 =new ArrayList();
    

    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 findById(@Param("id") int id);
    

    Here is a beginner friendly resource to start with JPA

提交回复
热议问题