【发布时间】:2019-11-24 22:28:54
【问题描述】:
我正在使用 spring-data-jpa。将子实体添加到父实体后,我将父实体保存到数据库。我想获取孩子的 id,但我发现我得到的是 null。
我在 getId() 方法中添加了@GeneratedValue(strategy = GenerationType.IDENTITY),但它不起作用。
这是型号:
@Entity
public class Parent {
private Integer id;
private List<Child> childList;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id")
public List<Child> getChildList() {
return childList;
}
// setters.....
}
@Entity
public class Child {
private Integer id;
private String name;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
@Cloumn("name")
public String getName() {
return name;
}
}
父实体已经在数据库中,所以我直接找到它,ParentRepository entends JpaReportory
这是我的测试代码:
Parent parent = parentRepository.findById(1);
Child child = new Child();
child.setName("child");
parent.getChildList().add(child);
parentRepository.save(parent);
System.out.println("child's id: " + child.getId());
我得到的输出是:
child's id: null
child 保存到数据库并且有id,但是内存中entity 的id 还是null,保存parent 后如何获取child 的id?而且因为我创建的子对象被其他对象引用,所以我需要只在这个子对象中获取 id,而不是从数据库中查找新对象。
【问题讨论】:
标签: java spring-data-jpa