java - 如何在Spring上获取没有关系的序列化对象

标签 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);
}

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

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"])

我知道 Jackson 试图序列化 Country 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());

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

关于java - 如何在Spring上获取没有关系的序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49344219/

相关文章:

java - Restrictions.sqlRestriction 参数索引超出范围

hibernate - Grails Row 被另一个事务更新或删除(或未保存值映射不正确)

java - 突发 "failed to lazily initialize a collection of role...:no session or session was closed"- 异常

java - 如何使用 JPA 在表末尾插入实体?

java - 两个类之间存在多个关联的 Hibernate 问题

java - 在 Postgres 上使用 JPA/Spring Boot 生成标题大小写字段

java - 编译成功但运行时出现错误

java - DialogFragment 正在将 XML 扩展到全屏?

java - 如果受影响的行数为零,则强制抛出异常

java - 自动装箱的性能影响