[英]I want to fetch the data from db dynamically in spring boot
I am building a rest api using spring boot framework.我正在使用 spring 引导框架构建 rest api。 I have a requirement to fetch data/columns(from several table) requested in the request using fields= creationDate,relatedParty[role,name].我需要使用 fields= creationDate,relatedParty[role,name] 获取请求中请求的数据/列(来自多个表)。 It must be dynamic fetch like whatever fields value come in request i need to fetch those particular data dynamically from db.它必须是动态获取,就像我需要从数据库中动态获取那些特定数据的请求中的任何字段值一样。
As far I understand your question I suggest you use one to many or many to many mapping based on your requirement.据我了解您的问题,我建议您根据您的要求使用一对多或多对多映射。 Like If I have a post model and a comment model and I want to fetch comments from the post model then I will use a one-to-many relationship.就像如果我有帖子 model 和评论 model 并且我想从帖子 model 中获取评论,那么我将使用一对多的关系。
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "title")
private String title;
@OneToMany(mappedBy = "post",
cascade = {CascadeType.ALL})
List<Comment> comments = new ArrayList<>();
}
And In the comment model, I will do this.在评论 model 中,我会这样做。
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String comment;
@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "posts_id", nullable = true)
private Post post;
}
There is no special support for this in Spring Data JPA, so you should fall back to JPA, ie you write a custom method and get an EntityManager
injected to work with. Spring 数据 JPA 对此没有特别支持,因此您应该退回到 JPA,即您编写自定义方法并使用注入的EntityManager
工作
You can use the Criteria API to create the query as you wish based on your input.您可以使用标准 API 根据您的输入创建查询。
This site should get you started with the Criteria API https://www.baeldung.com/hibernate-criteria-queries这个网站应该让你开始使用标准 API https://www.baeldung.com/hibernate-criteria-queries
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.