簡體   English   中英

如何在沒有彈簧關系的情況下獲取序列化對象

[英]How to get serialized object without their relationships on spring

我有下一個代碼:

我的實體:

@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]-> com.spring.demo.entity.Client [“ country”]-> com.spring.demo.entity.Country _ $$ _ jvst9a4_1 [“ handler”])

我了解傑克遜曾嘗試序列化國家/地區bean,但我的目的是僅獲取Client的主要參數,而不獲取其關系。

PD:我已經做了控制台要求我執行的操作:

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

這是可行的,但是作為第一種方法,因此不是一種選擇。

感謝前進。

嘗試添加以下內容:

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

根據您的版本休眠Hibernate5Module/4 or 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM