英文:
how to fetch data using Rest API in spring boot from multiple tables
问题
你好,我是新手编程,正在尝试在Spring Boot中创建一个REST API,该API从数据库中的4个表中获取数据,使用一个查询返回结果集。我该如何做这个?
英文:
hello am new to coding and am trying to create a rest api in spring boot that fetches data from 4 tables in the database which uses one query to return the result set. How can i do this.
答案1
得分: 0
你可以使用本地的SQL查询,但是所提到的用例可以通过HQL轻松实现。在此之前,让我们为ManyToMany关联使用适当的注解映射:
@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>();
}
查询语句:
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);
获取更多信息请参阅这里。
英文:
You can use a native SQL query, but the use case mentioned can be easily achieved with HQL. Before that, let's 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>();
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);
for more read here
专注分享java语言的经验与见解,让所有开发者获益!
评论