Play framework JPA: how to implement one-to-many r

2019-06-18 11:12发布

问题:

I have a Posts model and every post also contains Blocks (also a model). I'm using the play framework for this website, and what I want to do is show X number of post with all of it's blocks on one page. JPA (or play framework's implementation, don't know which one it is) has the find() method with which I could query for posts in my controller, and than I would send the post list to my view like this:

render(postList);

What I wanted to know is what would be the best way to send the blocks for each post to the view. I could add a getBlocks() method to my Post model, which sends back a blocksList, and call it from the view, but this seems messy to me, and it would defeat the purpose of MVC since the blocks would be fetched from the view.. (or am I wrong about this?)

Does JPA or Play! offer some way of retrieving the blocks together with the posts?

This is what my Post model looks like right now, without getters and setters:@Entity

@Table(name="posts")
public class Post extends GenericModel{

    @Id
    @Column(name="post_id")
    private int id;

    @Column(name="post_situation")
    private String situation;

    @Column(name="post_date")
    private Date date;

    @Column(name="post_userid")
    private int userid;

    private List<Block> blockList;
    public List<Block> getBlocks() {
        List<Block> block = null;
        return blockList;
    }

}

How should I do this?

回答1:

Just use the one-to-many keyword:

@OneToMany
private List<Block> blockList;

However it's not clear if you need the getBlocks method. If you are just getting the blocks from the database then you don't need this method.

Note: you probably want to read more on @OneToMany. You can for example add the option @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) such that when you persist or remove a Post from the database, the inner blockList does the same.