How to make a @ManyToOne field mandatory in JPA2?

孤街浪徒 提交于 2019-12-10 21:14:43

问题


I am designing the persistence repository for an app.

I am new to Hibernate+JPA2 and I am having trouble creating more complex relationships in this case a Foreign mandatory key.

An example (just wrote on notepad, so it's not exactly this.)

I have a Top Class called Person which can hold several Posts (another class).

If I map my top class like this

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

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

    .
    . more code
    .

}

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

    @Id
    @GeneratedValue
    public long         id;

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

    .
    .more code
    .

}

How can I using annotations make the person field in Post mandatory ?

I tryed with @Column(nullable=false) but I get an exception telling me I cannot use that annotation on a @ManyToOne Collection.

Thank you !


回答1:


You have to use @JoinColumn(name=..., nullable=false) not @Column

See the complete API




回答2:


Or you can just use @NotNull from javax.validations.constraints package.




回答3:


It should be enough to just use @ManyToOne(optional = false)



来源:https://stackoverflow.com/questions/5858113/how-to-make-a-manytoone-field-mandatory-in-jpa2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!