如何解决带有休眠惰性初始化对象的Spring Data Rest HAL响应格式问题
技术堆栈:Spring Boot(2.3.1.RELEASE),Spring Data JPA,Sprign Data Rest(3.3.1 RELEASE),Hibernate(5.4.17 Final),Postgresql。 我有上级实体 ProductEntity :
@Data
@Entity
@Table(name = "product")
@EntityListeners(AuditingEntityListener.class)
public class ProductEntity {
@NotNull
@Id
@EqualsAndHashCode.Exclude
@Type(type = "pg-uuid")
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2",strategy = "uuid2")
private UUID id;
@JsonProperty("productType")
@ToString.Exclude
@OnetoOne(mappedBy = "productEntity",cascade = CascadeType.ALL,fetch = FetchType.LAZY,orphanRemoval = true,optional = false)
private ProductTypeEntity productTypeEntity;
}
结束子实体 ProductTypeEntity :
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Entity
@Table(name = "product_type")
@JsonIgnoreProperties({"hibernateLazyInitializer"})
public class ProductTypeEntity extends BaseEntity implements RootAware<ProductEntity> {
@NotBlank
@Size(max = 255)
private String type;
@NotBlank
@Size(max = 255)
private String brand;
@OnetoOne(fetch = FetchType.LAZY,optional = false)
@MapsId
@JoinColumn(name = "id")
@ToString.Exclude
@EqualsAndHashCode.Exclude
@JsonIgnore
private ProductEntity productEntity;
@Override
public ProductEntity root() {
return productEntity;
}
}
最后有一个Spring Data REST存储库 ProductRepository :
@RepositoryRestResource(collectionResourceRel = "products",path = "products")
public interface ProductRepository extends JpaRepository<ProductEntity,UUID> {
}
主要问题是当我请求 GET http:// localhost:8081 / api / v1 / products 时,我收到了其他字段 content 在 productType 下是完全多余的,并且无法对响应进行足够的解析:
{
"_embedded": {
"products": [
{
"productType": {
"content": {
"type": "type1","brand": "brand1"
}
}
"_links": {
"self": {
"href": "http://localhost:8081/api/v1/products/6b0e375e-4d2d-41af-b42f-989859652c81"
},"productEntity": {
"href": "http://localhost:8081/api/v1/products/6b0e375e-4d2d-41af-b42f-989859652c81"
}
}
}
]
},"_links": {
"self": {
"href": "http://localhost:8081/api/v1/products"
},"profile": {
"href": "http://localhost:8081/api/v1/profile/products"
}
},"page": {
"size": 20,"totalElements": 1,"totalPages": 1,"number": 0
}
}
但是当我将productTypeEntity从 LAZY 更改为 EAGER 时:
@JsonProperty("productType")
@ToString.Exclude
@OnetoOne(mappedBy = "productEntity",fetch = FetchType.EAGER,optional = false)
private ProductTypeEntity productTypeEntity;
我收到正确的答复,但没有内容字段:
{
"_embedded": {
"products": [
{
"productType": {
"type": "type1","brand": "brand1","_links": {
"productEntity": {
"href": "http://localhost:8081/api/v1/products/6b0e375e-4d2d-41af-b42f-989859652c81"
}
}
},"_links": {
"self": {
"href": "http://localhost:8081/api/v1/products/6b0e375e-4d2d-41af-b42f-989859652c81"
},"number": 0
}
}
主要问题是此行为背后的原因是什么。我无法采用和使用它,因为我无法理解它的性质以及它是否可以解决。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。