简体   繁体   中英

I want to fetch the data from db dynamically in spring boot

I am building a rest api using spring boot framework. I have a requirement to fetch data/columns(from several table) requested in the request using 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.

@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.

@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.

You can use the Criteria API to create the query as you wish based on your input.

This site should get you started with the Criteria API https://www.baeldung.com/hibernate-criteria-queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM