【问题标题】:how to fetch data using Rest API in spring boot from multiple tables如何在 Spring Boot 中使用 Rest API 从多个表中获取数据
【发布时间】:2020-07-17 10:54:45
【问题描述】:

你好,我是编码新手,我正在尝试在 Spring Boot 中创建一个 rest api,它从数据库中的 4 个表中获取数据,该表使用一个查询来返回结果集。我怎样才能做到这一点。

【问题讨论】:

  • 总是添加一些你已经尝试过但对你不起作用的代码。

标签: java spring-boot rest jpa crud


【解决方案1】:

您可以使用原生 SQL 查询,但使用 HQL 可以轻松实现上述用例。在此之前,让我们为多对多关联使用正确的注解映射:

@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>();

产品

@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>();
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    相关资源
    最近更新 更多