Question

I have a similar table structure to the following:

Table_A(
  a_id,
  data,
  primary key(a_id)
)

Table_B(
  b_id,
  a_id,
  data,
  primary key (b_id),
  foreign key (a_id) references Table_A(a_id)
)

There is a one to many relationship between Table_A and Table_B. My question is, if I have an entity for each of these tables, where:

  • Entity Table_A is composed of a list of Table_B entities and
  • Entity Table_B does not necessarily need a reference to Table_A (just the fields b_id, a_id, data)

is it possible to annotate these entities in a way where I can persist a Table_A entity and the process will implicitly persist all Table_B entities with the value of the new generated Table_A primary key a_id.

Thanks in advance.

Here is what I have essentially . But I get the below exception. Looks like Table_B is being persisted prior to Table_A, therefore no a_id value exists.

@Entity
public class Table_A {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "a_id")
   private Integer id;

   @OneToMany (cascade = CascadeType.PERSIST)
   @JoinColumn(name="a_id")
   private List<Table_B> bList;

   private String data;
}

@Entity
public class Table_B {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "b_id")
   private Integer id;

   private String data;
}

ERROR: null value in column "a_id" violates not-null constraint Detail: Failing row contains (null, Testing, 16)

Was it helpful?

Solution

Yes, with a cascade set to PERSIST on the OneToMany association.

Note that you shouldn't have aId in the B entity. Either make the association bidirectional, and have a field of type TableA, or leave it unidirectional and don't have any field in B mapped to a_id.

EDIT: AFAIR, you need to tell Hibernate that the column is not null, else it tries to insert everything first, and then populate the foreign keys:

@OneToMany (cascade = CascadeType.PERSIST)
@JoinColumn(name="a_id", nullable=false)
private List<Table_B> bList;

OTHER TIPS

@OneToMany(mappedBy = "a_id", cascade = CascadeType.PERSIST)

instead of

@OneToMany(cascade = CascadeType.PERSIST) @JoinColumn(name="a_id")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top