我有一个User
(父)和Home
(子)实体在单向一对多关系之后相关.
我的问题是,当向a添加一个新Home
的时User
,新创建的和持久的Home
没有id
.这是正常的吗?如果我想要id,我是否需要手动保留孩子?
这些是我的实体:
@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 Listhomes; 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() { } }
以及更新父级的代码:
Home home = HomeParser.parse(homeDTO); User user = userService.findById(userId); user.addHome(home); userService.update(user); // delegate call to getEntityManager().merge(user);
在这一点上,我假设我必须home
拥有它在持久化到db时刚刚给出的id,但事实并非如此.
我已经尝试过添加insertable = false
到Home的id了@Column
,正如这里指出的那样,但它也不起作用.