0

Suppose we have an Employee entity, this entity has a reflexive relation (relation with itself). The kind of the relation is @ManyToOne mapping meaning, multiple Employee are supervised by only one "Boss" (who's also an Employee). Also Employee entity has relation with a Company entity.

Multiple Employee work for only one Company (@ManyToOne) and a Company know his boss (@OneToOne)

Question :

How can we persist this @ManyToOne and @OneToOne relation based on condition (criteria) ? We can assign (persist) a Boss to an Employee only if they work for the same company. And we can assign an Employee to a company only if he's the boss (means he hasn't supervisor (NULL)).

I guess there are many solution like using @Query, @Prepersist , @Filter, Do the checking in the service but how and which one is better for this case.

SRJ
  • 2,092
  • 3
  • 17
  • 36
  • This post might help you https://stackoverflow.com/questions/3393515/jpa-how-to-have-one-to-many-relation-of-the-same-entity-type – SRJ Oct 10 '22 at 04:50

1 Answers1

0

It can be achived using the below ,

@Entity
public class A implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    @ManyToOne
    private A parent;
    @OneToMany(mappedBy="parent")
    private Collection<A> children;

    // Getters, Setters, serialVersionUID, etc...
}

to check the relations, here's an driver code of MainApplication.java

public static void main(String[] args) {

    EntityManager em = ... // from EntityManagerFactory, injection, etc.

    em.getTransaction().begin();

    A parent   = new A();
    A son      = new A();
    A daughter = new A();

    son.setParent(parent);
    daughter.setParent(parent);
    parent.setChildren(Arrays.asList(son, daughter));

    em.persist(parent);
    em.persist(son);
    em.persist(daughter);

    em.getTransaction().commit();
}

if I set cascade=CascadeType.ALL on both of those annotations, I could safely persist one of the entities and ignore the others. Say I persisted parent in my transaction. The JPA implementation traverses parent's children property because it is marked with CascadeType.ALL. The JPA implementation finds son and daughter there. It then persists both children on my behalf, even though I didn't explicitly request it.

Shyam Patel
  • 381
  • 2
  • 13