简体   繁体   中英

How to get serialized object without their relationships on spring

I have the next code:

My entities:

@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...

My repository:

@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);
}

So, when I use the number one method works fine but when I try the number two the console throwing:

Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is com.tfasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.spring.demo.entity.Client["country"]->com.spring.demo.entity.Country_$$_jvst9a4_1["handler"])

I understand that jackson tried to serialize country bean but my purpose is get only the main parameters of Client not their relationships.

PD: I've already does that what console request me:

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

And this works but as the first method therefore isn't a option.

Thanks for advance.

Try adding this:

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

According to your version hibernate pick Hibernate5Module/4 or 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM