我正在当前项目中使用Spring Data Rest和Hibernate。我只是为某些实体添加了投影,以减少显示信息时对后端的调用量。我的代码如下:
Component.class
@NoArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode
@Getter
@Setter
@Slf4j
@Entity
@Table(name = "components")
public class Component
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "component_id", unique = true)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "component", cascade = {
CascadeType.DETACH,
CascadeType.PERSIST,
CascadeType.REFRESH
})
private List<Parameter> parameters = new ArrayList<>();
@NonNull
@Column(name = "name", nullable = false)
private String name;
}
Parameter.class
@AllArgsConstructor
@RequiredArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "parameters")
public class Parameter
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "parameter_id", unique = true)
private Long id;
@NonNull
@Column(name = "name", nullable = false, unique = true)
private String key;
@ManyToOne(fetch = FetchType.EAGER)
private Component component;
@Column(name = "type")
private String type;
}
投影课
@Projection(name = "withParameters", types = { Component.class })
public interface ComponentWithParameters
{
Long getId();
String getName();
List<Parameter> getParameters();
}
投影应将参数完美地添加到组件中:
{
"name" : "New Component",
"id" : 1,
"parameters" : [ {
"id" : 1,
"key" : "Parameter_2",
"type" : null
}, {
"id" : 2,
"key" : "Parameter_19",
"type" : null
}, {
"id" : 18,
"key" : "Parameter_9",
"type" : null
} ],
"_links" : {
"self" : {
"href" : "https://localhost:8020/api/components/1"
},
"component" : {
"href" : "https://localhost:8020/api/components/1{?projection}",
"templated" : true
},
"parameters" : {
"href" : "https://localhost:8020/api/components/1/parameters{?projection}",
"templated" : true
}
}
}
我期望列表中的参数具有Spring Data Rest通常应用的所有链接。像这样:
{
"name" : "New Component",
"id" : 1,
"parameters" : [ {
"id" : 1,
"key" : "Parameter_2",
"type" : null,
"_links":{
"self":{
"href":"http://localhost:8080/api/parameters/1{?projection}",
"templated":true
},
"component":{
"href":"http://localhost:8080/api/parameters/1/component"
}
}
}, {
"id" : 2,
"key" : "Parameter_19",
"type" : null,
"_links":{
"self":{
"href":"http://localhost:8080/api/parameters/2{?projection}",
"templated":true
},
"component":{
"href":"http://localhost:8080/api/parameters/2/component"
}
}
}, {
"id" : 18,
"key" : "Parameter_9",
"type" : null,
"_links":{
"self":{
"href":"http://localhost:8080/api/parameters/18{?projection}",
"templated":true
},
"component":{
"href":"http://localhost:8080/api/parameters/18/component"
}
}
} ],
"_links" : {
"self" : {
"href" : "https://localhost:8020/api/components/1"
},
"component" : {
"href" : "https://localhost:8020/api/components/1{?projection}",
"templated" : true
},
"parameters" : {
"href" : "https://localhost:8020/api/components/1/parameters{?projection}",
"templated" : true
}
}
}
我发现了一个this问题,这个问题与我的非常相似,而且显然是一个错误,我想知道这一次是否又是一个问题。
我正在使用以下版本:
希望有人可以帮助我解决这个问题。谢谢大家。