我正在使用Spring 1.3.3,我无法使用GET获取嵌入式类的关联对象。它在使用投影时返回URI而不是对象。
{
"employeeId": {
"empId": 4,
"_links": {
"address": {
"href": "http://localhost:8082/address/1"
},
"zipcode": {
"href": "http://localhost:8082/zipcode/2"
}
}
},
"empId": 4,
"name": "ap",
},
"_links": {
"self": {
"href": "http://localhost:8082/employee/com.blah.blah.Employee@64f11498"
},
"adNetworkParam": {
"href": "http://localhost:8082/employee/com.blah.blah.EmployeeId@64f11498{?projection}",
"templated": true
},
"demandSource": {
"href": "http://localhost:8082/employee/com.blah.blah.EmployeeId@64f11498/address"
},
"targetCharacteristic": {
"href": "http://localhost:8082/employee/com.blah.blah.EmployeeId@64f11498/zipcode"
}
}
}
我的域类如下..
Employee.java
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
private EmployeeId employeeId;
private Address address;
private Zipcode zipcode;
private int empId;
private String name;
//getter
...
@MapsId("address")
@ManyToOne
@JoinColumn(name = "address_id")
public Address getAddress() {
return address;
}
@MapsId("zipcode")
@ManyToOne
@JoinColumn(name = "zipcode_id")
public Zipcode getZipcode() {
return zipcode;
}
// setter
.....
Address.java
@Entity
@Table(name="address")
public class Address implements Serializable {
private int id;
private String streetName;
private String cityName
Zipcode.java
@Entity
@Table(name = "zipcode")
public class Zipcode implements Serializable {
@Id
@GeneratedValue
private int id;
private String code;
EmployeeId.java
@Embeddable
public class EmployeeId implements Serializable {
private Address address;
private Zipcode zipcode;
private int empId;
我的投影如下,
@Projection(name = "employeeProjection", types = { Employee.class })
public interface EmployeeProjection {
Address getAddress();
Zipcode getZipcode();
int getEmpId();
String getName();
}
员工搜索存储库类如下,
@RepositoryRestResource(excerptProjection = EmployeeProjection.class)
interface EmployeeRepository extends CrudRepository<Employee, EmployeeId> {
List<Employee> findByNameContaining(@Param("name") @RequestParam("name") String name);
Employee findById(@Param("employeeId") @RequestParam("employeeId") Integer employeeId);
}
如何返回关联对象而不是嵌入类的URI?
请提供您的意见。
答案 0 :(得分:0)
您应该在存储库定义中使用摘录。我可以根据您的GET结果猜测,Employee存储库如下:
interface EmployeeRepository extends CrudRepository<Employee, EmployeeId> {}
将其更改为:
@RepositoryRestResource(excerptProjection = EmployeeProjection.class)
interface EmployeeRepository extends CrudRepository<Employee, EmployeeId> {}
这将导致zipCode和地址被内联。请注意,内联资源的链接仍会显示在投影中。
应修改员工模型,并使用嵌入式成员上方的@OneToOne注释进行定义:
@Table(name = "employee")
public class Employee implements Serializable {
private EmployeeId employeeId;
@OneToOne
private Address address;
@OneToOne
private Zipcode zipcode;
private int empId;
private String name;
您可以在spring doc中阅读更多内容。