如何在没有弹簧关系的情况下获得序列化对象

时间:2018-03-18 03:29:52

标签: java hibernate jpa spring-boot jackson

我有下一个代码:

我的实体:

@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:没有为类org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer找到序列化器,也没有发现创建BeanSerializer的属性(为了避免异常,禁用SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过参考链) :java.util.ArrayList [0] - &gt; com.spring.demo.entity.Client [&#34; country&#34;] - &gt; com.spring.demo.entity.Country _ $$ _ jvst9a4_1 [&#34 ;处理&#34;])

我知道杰克逊试图序列化国家豆,但我的目的只是得到客户的主要参数而不是他们的关系。

PD:我已经知道控制台要求我了:

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

这是有效的,但因为第一种方法不是一种选择。

感谢您提前。

1 个答案:

答案 0 :(得分:1)

尝试添加此内容:

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

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