I have 3 table.
Table A has column primary key X which is a foreign key in Table B. Table B has a column primary key Y which is a foreign key in Table C.
I created entities for these tables.In Entity A I marked Entity B as OneroMany and in Entity B i marked Entity A and ManyToOne and Entity C as OneToMany and in Entity C I marked Entity B as ManyToOne
Now when I do a save I am getting exception from Entity C that that join column with Entity B is null.
Can you help me on how to configure this multilevel dependency?
I created entities for these tables.In Entity A I marked Entity B as OneroMany and in Entity B i marked Entity A and ManyToOne and Entity C as OneToMany and in Entity C I marked Entity B as ManyToOne
Now when I do a save I am getting exception from Entity C that that join column with Entity B is null.
Can you help me on how to configure this multilevel dependency?
CodePudding user response:
This seems pretty straight out of JPA tutorials:
@Entity
class EntityA {
@Id
@GeneratedValue
@Column(name="X")
Integer id;
@OneToMany(mappedBy = "entityA",cascade=CascadeType.PERSIST)
List<EntityB> entityBs;
}
@Entity
class EntityB {
@Id
@GeneratedValue
@Column(name="Y")
Integer id;
@ManyToOne//defaults to using entityA_id as the fk column name
EntityA entityA;
@OneToMany(mappedBy = "entityB",cascade=CascadeType.PERSIST)
List<EntityC> entityCs;
}
@Entity
class EntityC {
@Id
@GeneratedValue
Integer id;
@ManyToOne
EntityB entityB;
}
I normally don't recommend having cascade options set, but did here just to show how I'd persist such a model using only the Root EntityA in a graph:
{
EntityA a = new EntityA();
EntityB b1 = new EntityB();
a.getEntityBs().add(b1);
b1.setEntityA(a);//set both sides of this relationship!
EntityC c1 = new EntityC();
b1.getEntityCs().add(c1);
c1.setEntityB(b1);//set both sides of this relationship!
entityManager.getTransaction().begin();
entityManager.persist(a);
entityManager.getTransaction().commit();
}
JPA will automatically assign ID values in to A and B and set the foreign keys into C and B from those values on the commit call.