我有下一个代码:
我的实体:
@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/