I have a User
(parent) and a Home
(child) entities related following a unidirectional one-to-many relationship.
My problem is that, when adding a new Home
to a User
, the newly created and persisted Home
doesn't have the id
. Is this normal? Do I need to manually persist the child if I want the id?
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 I would have home
to have the id that it's just been given when persisted to db, but it doesn't.
I already tried adding insertable = false
to the Home's id's @Column
, as pointed here, but it doesn't work either.
EntityManager.merge
method implementation delegates to Hibernate Session.merge
:
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with
cascade="merge"
.
Notice the part in bold. Basically, the merge
operation will be cascaded to the Home
instance you created, but Hibernate will create a copy of that instance, merge your instance into the copy, save the copy and replace your instance with the copy in the User.homes
collection.
After this, User.homes
collection should contain the copy of the Home
instance with a properly initialized id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With