【问题标题】:How to get serialized object without their relationships on spring如何在没有关系的情况下获取序列化对象
【发布时间】:2018-08-26 21:45:25
【问题描述】:

我有下一个代码:

我的实体:

@Entity
@NamedEntityGraphs({
        @NamedEntityGraph(
        name = "client",
        attributeNodes = {
                @NamedAttributeNode( value = "country" )}),
        @NamedEntityGraph(
        name = "only_client",
        attributeNodes = {})
        })
public class Client{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="ClientId")
    private int id;
    private String firstName;
    private String lastName;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CountryId")
    private Country country;

    //Constructor, getters and setters...
}
//Country class...

我的仓库:

@Repository
public interface ClienteRepository extends JpaRepository<Cliente, Serializable> {

    // #1
    @Override
    @EntityGraph(value = "client",type = EntityGraph.EntityGraphType.FETCH)
    List<Cliente> findAll();

    // #2
    @EntityGraph(value = "only_client")
    List<Cliente>  findAllByLastNameContaining(String lastName);
}

所以,当我使用第一种方法时效果很好,但是当我尝试第二种方法时,控制台抛出:

无法写入 JSON:没有为类 org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 找到序列化程序,也没有发现用于创建 BeanSerializer 的属性(为避免异常,请禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS);嵌套异常是 com.tfasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 也没有发现创建 BeanSerializer 的属性(为避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链: java.util.ArrayList[0]->com.spring.demo.entity.Client["country"]->com.spring.demo.entity.Country_$$_jvst9a4_1["handler"])

我知道 jackson 试图序列化 country bean,但我的目的是只获取 Client 的主要参数而不是它们的关系。

PD:我已经按照控制台的要求做到了:

ObjectMapper objMapper = new ObjectMapper();
objMapper .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
return objMapper .writeValueAsString(listOnlyClient)

这可行,但作为第一种方法,因此不是一种选择。

感谢您的提前。

【问题讨论】:

    标签: java hibernate jpa spring-boot jackson


    【解决方案1】:

    尝试添加这个:

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Hibernate5Module());
    

    根据你的版本hibernate选择Hibernate5Module/4 or 3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-04
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      相关资源
      最近更新 更多