问题
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