No child identifier after cascade storing parent

I have child objects User (parent) and Home (children) associated with a one-to-one relationship to many.

My problem is that when adding a new Home to User , the newly created and saved Home will not have an id . This is normal? Do I need to manually hold the child if I want an identifier?

These are my entities:

 @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @NotNull @Column(name = "firstName") private String firstName; @NotNull @Column(name = "lastName") private String lastName; @NotNull @Column(name = "email") private String email; @OneToMany(targetEntity = Home.class, fetch = FetchType.EAGER, cascade = {CascadeType.ALL}, orphanRemoval = true) @JoinColumn(name = "userId", referencedColumnName = "id", nullable = false) private List<Home> homes; public User() { } public void addHome(Home home) { homes.add(home); } } @Entity @Table(name = "home") public class Home implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @NotNull @Column(name = "isActive") private Boolean isActive; public Home() { } } 

And the code to update the parent:

 Home home = HomeParser.parse(homeDTO); User user = userService.findById(userId); user.addHome(home); userService.update(user); // delegate call to getEntityManager().merge(user); 

At this point, I assumed that I would have Home , so that the identifier was specified only when saving db, but this is not the case.

I have already tried adding insertable = false to the Home id @Column , as indicated here , but it does not work either.

+8
java hibernate jpa one-to-many
source share
1 answer

EntityManager.merge function execution command for Hibernate Session.merge :

Copy the state of this object to a permanent object using the same identifier. If there is currently no persistent instance associated with the session, it will be loaded. Return a constant example. If this instance is not saved, save a copy and return it as a new permanent instance. This instance does not become associated with the session. This operation cascades associated instances if the association is mapped to cascade="merge" .

Pay attention to the part in bold. Basically, the merge operation will be cascaded in the instance of Home you created, but Hibernate will create a copy of this instance, merge your instance into a copy, save the copy and replace your instance with a copy in the User.homes collection.

After that, the User.homes collection should contain a copy of the Home instance with a correctly initialized identifier.

+4
source share

All Articles