How to make a @ManyToOne field mandatory in JPA2?
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 Perso开发者_如何转开发n{
@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 !
You have to use @JoinColumn(name=..., nullable=false)
not @Column
See the complete API
Or you can just use @NotNull from javax.validations.constraints package.
It should be enough to just use @ManyToOne(optional = false)
精彩评论