Hi,
I am having a problem that Hibernate is not assigning the generated id from the database to the instances that were created. The specific problem I am working on is one-to-many association, where the whole has a list of parts.
Here are the entities used:
Code:
@Entity
public class Whole {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@OneToMany(cascade={CascadeType.ALL})
@JoinColumn(name="whole_id", nullable=false, updatable=false)
private List<Part> parts;
...
}
Code:
@Entity
public class Part {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
...
}
And now the problem.
When I try to insert a new Part in the list and call merge(), Hibernate will not assign the id to the newly created Part in the database. But I need the id of the object that was created, and I don't want to create another query. It should have already been set, because there is a query to the new id in the log.
Here is the test that fails:
Code:
@Test
public void testUpdateLoadsId() throws Exception {
Whole whole = em.find(Whole.class, wholeId);
Part part = new Part();
whole.getParts().add(part);
em.merge(whole);
em.flush();
Assert.assertNotNull(part.getId());
}
But if I remove the call to flush(), the test does not fail:
Code:
@Test
public void testAnotherUpdateLoadsId() throws Exception {
Whole whole = em.find(Whole.class, wholeId);
Part part = new Part();
whole.getParts().add(part);
em.flush();
Assert.assertNotNull(part.getId());
}
Both of them generate the same sql:
Code:
Hibernate: select whole0_.id as id0_0_ from Whole whole0_ where whole0_.id=?
Hibernate: select parts0_.whole_id as whole2_1_, parts0_.id as id1_, parts0_.id as id1_0_ from Part parts0_ where parts0_.whole_id=?
Hibernate: insert into Part (whole_id) values (?)
Hibernate: select currval('Part_id_seq')
As can be seen above, Hibernate queries the database for the new id. But it is not assigning it to the instance.
I don't know if it is a bug or a feature.
Please don't tell me to just use the option that works. The code above is just an example to show that something is wrong. In my actual implementation, the Whole instance is a detached entity, so I will have to call merge() anyway.
Thanks in advance.
I am using the latest versions of Hibernate:
Hibernate Core 3.3.0 SP1
Hibernate Annotations 3.4.0 GA
Hibernate EntityManager 3.4.0 GA