1

I have a @OneToMany relationship between Table1 and Table2 in Hibernate. Table1 is the owner, and the relationship is one-directional-- i haven't mapped Table2 back to Table1.

So, as part of this, I defined a Collection of Table2 instances for this @OneToMany mapping. and I'm cascading-all.

In this "scenario", i'm looking to add a collection of Table2 instances, say table2_a, table2_b and table2_c as related to a Table1 object, say table1.

Is there a way to do this insertion on saving the owner class instance, table1, and thus having the dependent class instances table2_a, table2_b and table2_c saved on cascade? When i attempt to do this, i'm getting an error that

Duplicate entry '23' for key ...

Hibernate is attempting to save all of table2_a, table2_b and table2_c on the same Table2 key value generated for the corresponding Table1 instance in the session. So, how do i put to use the "Many" side of @OneToMany here ?

Is there a way to do this insertion with the uni-directional mapping as is-- without mapping also Table2 to Table1, on @ManyToOne, for the other side of the relationship? I'm looking to keep the tables light.

The code is working on insertion of a single Table2 instance in the collection, and everything else is fine.

//===========================

EDIT: the relevant parts of the code:

the relationship defined in Table1-- the entity class:

@OneToMany(cascade = CascadeType.ALL)
private Collection<Table2> table2Inst = new ArrayList<>();
// getter & setter

the code doing the save in pojo:

    table1 = (Table1)session.get(Table1.class, theId);

    if ( table1!=null ) {
        table1.getTable2Inst().addAll(contactsList);
        session.saveOrUpdate(table1);  
    }

Note: i'm defining it all on the entity class. there's nothing in mapping files.

Roam
  • 4,831
  • 9
  • 43
  • 72

1 Answers1

0

did't you need to add mappedBy = "table1Id" or something in that one to many? like this.

@OneToMany(cascade = CascadeType.ALL, mappedBy = "table1Id");//table1Id is foreign key of table1 in table2
private Collection<Table2> table2Inst = new ArrayList<>();

and did you make sure that contactsList is composed from all new object new table2()?

Angga
  • 2,305
  • 1
  • 17
  • 21