I'm using spring-data-jpa. After adding a child to parent entity, i save the parent to database. I'd like to get the child's id, but I found what I get is null.
I added @GeneratedValue(strategy = GenerationType.IDENTITY) to getId() method, but it didn't work.
here is model:
@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;
}
}
the parent entity is already in database, so i find it directly, ParentRepository entends JpaReportory
here is my test code:
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());
the output i get is:
child's id: null
the child is saved to database and has id, but the id of entity in memory is still null, how can I get child's id after saving parent? And because the child I create was cited by other object, i need to get id just in this child rather than find a new object from database.