json - 在 spring data rest 中序列化时获取惰性对象

标签 json spring hibernate spring-data spring-data-rest

我有一个具有某些属性的实体 A,并引用了另一个实体 B

A{
....
   @ManyToOne(fetch=FetchType.LAZY)
   B b;
...
}

B 相同(@onetomany 用于 B 中的 A)。它是双向关系。 在为实体 A 调用 Web 服务时,它会在响应 json 中提供指向 B 实体的链接,而不是整个对象。 我想要 Web 服务响应 JSON 中的整个对象,而不是指向相关实体的链接。 我怎样才能做到这一点? 我正在使用 springboot + spring data jpa + hibernate 作为 jpa 提供程序 + spring 4

最佳答案

为了在输出 JSON 中嵌套相关对象,您必须使用 projections .

public class User {
   private String name;
   private Address address;
}

public class Address {
   private String street;
}

public interface UsersRepository extends JpaRepository<User, Long> {
   // Custom methods
}

给你

{
   "name": "John",
   "_links": {
      "self": "http://localhost:8080/users/1",
      "address": "http://localhost:8080/addresses/1"
   }
}

但是有投影:

@Projection(name = "inlineAddress", types = { User.class })
public interface UserInlineAddressProjection {
   String getName();
   Address getAddress();
}

@RepositoryRestResource(excerptProjection = UserInlineAddressProjection.class)
public interface UsersRepository extends JpaRepository<User, Long> {
   // Custom methods
}

结果如下:

{
    "name": "John",
    "address": {
       "street": "Stormtroopers str. 1"
    },
    "_links": {
       "self": "http://localhost:8080/users/1",
       "address": "http://localhost:8080/addresses/1"
    }
}

这是实现它的唯一方法

关于json - 在 spring data rest 中序列化时获取惰性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29118193/

相关文章:

json - 使用 Swift 访问 Shippo API 返回未记录的错误

javascript - Ajax HTTP 请求使用请求正文中的数组更改 JSON

java - 当 cfg 文件和实体文件位于不同文件夹中时的 Hibernate 映射

hibernate - 如果我们将查询与GORM一起使用会降低性能问题?

jquery ajax调用返回JSON解析错误

json - 在 Postgres 中使用两个 JSONB 键进行数学计算?

主方法类中的 Spring bean 注入(inject)

spring - 无法让 OpenEntityManagerInViewFilter 在 JBoss 6.1 中工作

spring - 通过 thymeleaf sec 标签与 spring security 一起获取当前用户的额外信息

java - 重写 toString() 方法时出现 StackOverflow 错误