我有两个模型类Gizmo和GizmoChild。我通过保存gizmoChild对象来保存gizmo对象。 Gizmo对象正确保存,但在GimoChild表中,gizmo id为NULL。

Gizmo模型:

  @Entity
  public class Gizmo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long Id;
    private String field1;
    private String field2;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "gizmo", fetch =
    FetchType.LAZY)
    private List<GizmoChild> children;
 }


GizmoChild模型:

@Entity
public class GizmoChild {
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private Long Id;
 private String childField1;
 private String childField2;
 @ManyToOne
 private Gizmo gizmo;
}


Gimo储存库:

@Repository
public interface GizmoRepository extends JpaRepository<Gizmo, Long> {
}


GizmoService:

@Service
public class GizmoService {

@Autowired
 private GizmoRepository gizmoRepository;

 public void save(Gizmo gizmo){
    gizmoRepository.save(gizmo);
}


控制器:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveGizmo(Model model){
    Gizmo gizmo1 = new Gizmo();
    gizmo1.setField1("Field1");
    gizmo1.setField2("Field2");

    GizmoChild gizmoChild = new GizmoChild();
    gizmoChild.setChildField1("ChildField1");
    gizmoChild.setChildField2("ChildField2");

    gizmo1.getChildren().add(gizmoChild);

    gizmoService.save(gizmo1);
    return "redirect:/";
}


我创建的是Gizmo对象,而不是创建的GizmoChild,并将它们添加到列表中。 Gizmo正在保存,但未插入GizmoChild表gizmo ID。如何摆脱这个问题?

最佳答案

首先您也可以添加GizmoChildRepository,Gizmo和GizmoChild的原因是您的不同实体对象:

@Repository
public interface GizmoChildRepository extends JpaRepository<GizmoChild, Long> {
}


然后更改服务方法save(Gizmo gizmo)来持久保存GizmoChild数据。

GizmoService:

@Service
public class GizmoService {

@Autowired
private GizmoRepository gizmoRepository;

@Autowired
private GizmoChildRepository gizmoChildRepository;

public void save(Gizmo gizmo) {
   for(GizmoChild child : gizmo.getChildren()) {
       gizmoChildRepository.save(child);
   }
   gizmoRepository.save(gizmo);
}

07-24 09:28