Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditions for JPA OneToMany collection

If I have this entity:

@Entity class Pet {      @Id     long id;      public enum State { ALIVE, DEAD }      @Enumerated(EnumType.STRING)     @...     State state;      @...     String name;  } 

Can I create a mapping like this:

@Entity class Owner {      @OneToMany(condition="state = ALIVE") // or something like that     Set<Pet> alivePets;      @OneToMany(condition="state = DEAD")     Set<Pet> deadPets;  } 
like image 831
Bart van Heukelom Avatar asked Mar 27 '12 19:03

Bart van Heukelom


People also ask

Can a JPA entity have multiple OneToMany associations?

You can have multiple one-to-many associations, as long as only one is EAGER.

How do I map OneToMany?

Create an entity class Student. java under com. javatpoint. mapping package that contains student id (s_id), student name (s_name) with @OneToMany annotation that contains Library class object of List type.

How does JPA define Many-To-One relationships?

Many-To-One relation between entities: Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns) which contain unique values. In relational databases these relations are applicable by using foreign key/primary key between tables.

How do you implement a one to many relationship in Java?

You can ensure that there are no duplicates by using a Set implementation like HashSet instead of using other data-structure. And instead of adding Job to a customer, create an final inner class in Job class that has private constructor. That ensure that the wrapper inner class can only be created by a job object.


1 Answers

As far as I know this is not part of the JPA spec. At least Hibernates JPA implementation provides an own annotation @Where which can be used:

@OneToMany @Where(clause = "state = 'ALIVE'") Set<Pet> alivePets 
like image 198
magomi Avatar answered Sep 23 '22 10:09

magomi