要将@OneToMany关系对象与子对象一起插入,而不在子表中插入父ID?

时间:2019-05-03 17:24:11

标签: java spring spring-boot spring-mvc jpa

我有两个模型类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;
}

GimoRepository:

@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:/";
}

与创建GizmoChild并将其添加到列表中相比,我正在创建Gizmo对象。 Gizmo正在保存,但未插入GizmoChild表gizmo ID。如何摆脱这个问题?

2 个答案:

答案 0 :(得分:0)

首先您也可以添加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);
}

答案 1 :(得分:0)

您可以尝试以下方法:

@OneToMany(cascade=CascadeType.ALL, mappedBy="gizmo")
private Set<GizmoChild> workOrders;

@ManyToOne(optional=false)
@JoinColumn(name="gizmo_id", referencedColumnName="id")
private Gizmo gizmo;