spring-data-rest spring-data-jpa不保存子实体

时间:2019-05-13 18:29:57

标签: hibernate spring-boot jpa spring-data-jpa spring-data-rest

一个简单的单向OneToOne映射。

实体

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"})
@Data 
public abstract class ID implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private UUID id;
}

@RequiredArgsConstructor(onConstructor = @__(@PersistenceConstructor))
@AllArgsConstructor
@Builder
@Data
@Entity(name = "gencontractor")
@Table(name = "gencontractor")
public class GenContractor extends ID {

    @Column(updatable = false)
    private String email;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "address_id", referencedColumnName = "id")
    private Address address;
}

@RequiredArgsConstructor(onConstructor = @__(@PersistenceConstructor))
@AllArgsConstructor
@Builder
@Data
@Entity(name = "address")
@Table(name = "address")
public class Address extends ID {

    @Column
    private String name;

    @Column
    private String street;

    @Column
    private String city;

    @Column
    private String phone;
}

表地址的PK为“ id”。表GenContractor具有PK“ id”和外键“ address_id”到Address.id。

存储库

@RepositoryRestResource(collectionResourceRel = "gencontractors", path = "gencontractors")
public interface GenContractorRepository extends JpaRepository<GenContractor, UUID> {
}
@RepositoryRestResource(collectionResourceRel = "addresses", path = "addresses")
public interface AddressRepository extends JpaRepository<Address, UUID> {
}

当我发布/ gencontractors {“ email:” bla“,” address“:{” name“:” bla“,...}}时,地址没有保存到Address表中。

我想念什么?

1 个答案:

答案 0 :(得分:0)

地址不是是嵌入式对象,因此您不能直接通过父对象写入其属性。

您需要分两步创建对象:

  1. POST /地址{“ name”:“ bla”,...}
  2. 它返回到新创建的对象的链接-> http://.../gencontractors/X。您需要使用此链接作为地址:
  3. POST / gencontractors {“电子邮件:” bla“,”地址“:” http://.../gencontractors/X“}