如何在JPA2中使@OneToMany字段变为必填?

huangapple 未分类评论45阅读模式
英文:

How to make a @OneToMany field mandatory in JPA2?

问题

我正在为一个应用程序设计持久性存储库。

我以这段代码作为示例:https://stackoverflow.com/questions/5858113/how-to-make-a-manytoone-field-mandatory-in-jpa2,但我需要相反的情况。
在我的情况下,每个人都必须至少有一篇文章。

你可以帮助我吗?

@Entity
@Table(name="tb_people")
public class Person{
    @Id
    @GeneratedValue
    public long id;

    @OneToMany(mappedBy="person")
    List<Post> listOfPosts;

    //.... 一些代码
}

@Entity
@Table(name="tb_posts")
public class Post{

    @Id
    @GeneratedValue
    public long id;

    @ManyToOne
    @JoinColumn(name = "person_id")
    Person person;

    //.... 一些代码
}
英文:

I am designing the persistence repository for an app.

I took this list of code as example https://stackoverflow.com/questions/5858113/how-to-make-a-manytoone-field-mandatory-in-jpa2 , but I need the opposite scenario.
In my case each person must have at least one Post.

Could you help me with this?

@Entity
@Table(name=&quot;tb_people&quot;)
public class Person{
    @Id
    @GeneratedValue
    public long         id;

    @OneToMany(mappedBy=&quot;person&quot;)
    List&lt;Post&gt;          listOfPosts;

    //.... some code
}
@Entity
@Table(name=&quot;tb_posts&quot;)
public class Post{

    @Id
    @GeneratedValue
    public long         id;

    @ManyToOne
    @JoinColumn(name = &quot;person_id&quot;)
    Person              person;

    //.... some code
}

huangapple
  • 本文由 发表于 2020年4月3日 22:04:12
  • 转载请务必保留本文链接:https://java.coder-hub.com/61013651.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定