Thanthla
Thanthla

Reputation: 586

Hibernate: Allow only entities with given attribut to a OneToMany association

Is it possible to check in a @OneToManyor @ManyToMany association if the many side has a given attribut value?

For example, students visiting a lecture:

@Entity
class Lecture implements Serializable {
  @Id
  Integer id;

  @OneToMany
  Set<Student> student;
}

@Entity
class Student implements Serializable {
  @Id
  Integer id;

  Boolean isFemale; 
}

Can I enforce with a "magic" annotation that only female students are allowed to visit the lecture?

Upvotes: 0

Views: 105

Answers (1)

Mick
Mick

Reputation: 973

Your @OneToMany annotation will execute a SELECT statement. You might be able to filter the result with vendor proprietary annotations like @Where (https://forum.hibernate.org/viewtopic.php?f=1&t=1026210&view=next).

But it seems that you want to restrict the INSERT case. You might just use a Java bean validator. So, if your Student class had the reverse @ManyToOne attribute lecture, then you could create a validator which rejects new student objects, which are linked to a lecture AND are female. (thus implementing your desired discrimination) (see bean validation: https://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.html#section-class-level-constraints)

But you might have guessed yourself that your constraint is not a real database constraint. It's not possible with SQL, so don't expect it to be possible with JPA.

Upvotes: 1

Related Questions