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.
java hibernate jpa one-to-many
user3748908
source share