Hibernate ORM:保存 Parent 实体也保存 Children?

Hibernate ORM: Saving Parent Entity Saves the Children too?

我有以下 JSON 作为输入:

{
  "type": "Student",
  "numOfPeople": "1",
  "tenantMembers": [
    {
      "firstName": "Chris",
      "lastName": "C"
    }
  ],
  "tenantDetails": {
    "firstName": "John",
    "lastName": "J",
    "email" "xyz@gmail.com"
  }
}

我想用它来保存:

tenantRepo.save(tenant);

这应该保存parent"Tenant"和children "TenantMembers"和"TenantDetails".

但是当我这样做时,children 中的 'tenant_id's 为 NULL。 (如果我在数据库中有外键给出 'tenant_id' can't be null constraint exception)

我的问题是:在 Hibernate 中这可能吗?

我的模特:

Parent class:

@Entity
@Table(name = "tenant")
public class Tenant {

@GeneratedValue
@Id
private Long id;

private String type;

@Column(name = "num_of_people")
private String numOfPeople;

@OneToMany(mappedBy = "tenant", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<TenantMember> tenantMembers;

@OneToOne(mappedBy = "tenant", cascade = CascadeType.ALL)
private TenantDetails tenantDetails;

TenantMember child class:

@Entity
@Table(name = "tenant_member")
public class TenantMember {
@GeneratedValue
@Id
private Long id;

@ManyToOne
@JoinColumn(name = "tenant_id")
private Tenant tenant;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

租户详情child class:

@Entity
@Table(name="tenant_details")
public class TenantDetails {
@GeneratedValue
@Id
private Long id;

@OneToOne
@JoinColumn(name = "tenant_id")
private Tenant tenant;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

private String email;

编辑:

根据 Dragan Bozanovic 的建议,尝试使用@JsonIdentityInfo 对于三个表:

@Entity
@Table(name = "tenant")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Tenant {


@Entity
@Table(name="tenant_details")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class TenantDetails {


@Entity
@Table(name = "tenant_member")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class TenantMember {

并执行以下操作来保存:

@RequestMapping(value = "/set", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Tenant test(@RequestBody Tenant tenant) {
    Tenant t = new Tenant();
    t.setType(tenant.getType());
    t.setNumOfPeople(tenant.getNumOfPeople());
    tenantRepo.save(t);
    tenant.setId(t.getId());
    tenant.getTenantDetails().setTenant(tenant);
    for(TenantMember member: tenant.getTenantMembers()) {
        member.setTenant(tenant);
    }
    return tenantRepo.save(tenant);
}

这是可能的最佳方法吗?

由于您指定的级联选项,Hibernate 会保存子项(因此会违反约束),但它不会保存您的情况下的关系信息(连接列值)。

TenantMemberTenantDetails 是与 Tenant 关联的所有者(Tenant 中关联注释中的 mappedBy 属性)。

这意味着您必须正确更新 TenantMemberTenantDetails 实例中的 tenant 字段,因为 Hibernate 在维护关系时会忽略关联的反面。