Play框架JPA:如何实现一对多关系? [英] Play framework JPA: how to implement one-to-many relationship?

查看:134
本文介绍了Play框架JPA:如何实现一对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Posts模型,每个帖子还包含Blocks(也是一个模型).我正在使用该网站的播放框架,我想做的是在一页上显示X帖子的数量及其所有块. JPA(或播放框架的实现,不知道它是哪个)具有find()方法,通过该方法我可以在控制器中查询帖子,然后将帖子列表发送到我的视图中,如下所示:

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

我想知道的是将每个帖子的块发送到视图的最佳方法是什么.我可以在Post模型中添加一个getBlocks()方法,该方法发送回一个blocksList并从视图中调用它,但是这对我来说似乎很杂乱,并且由于将从视图中获取块而使MVC的目的无法实现. ..(或者我对此有误吗?)

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?)

JPA还是Play!提供一些与帖子一起检索块的方法吗?

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

这是我的Post模型现在的样子,没有getter和setter:@Entity

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;
    }

}

我应该怎么做?

推荐答案

只需使用一对多关键字:

Just use the one-to-many keyword:

@OneToMany
private List<Block> blockList;

但是尚不清楚是否需要getBlocks方法.如果您只是从数据库中获取块,则不需要此方法.

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.

注意:您可能想了解有关@OneToMany的更多信息.例如,您可以添加选项@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}),这样当您持久化数据库或从数据库中删除Post时,内部的blockList会执行相同的操作.

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.

这篇关于Play框架JPA:如何实现一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆