java - Hibernate HttpMessageNotWritableException

标签 java spring hibernate

我目前在 Spring MVC 4.2.3 中使用 Hibernate 4.3.5。我有两个模型 UserClient,其中 UseridClient< 的外键

User类中:

@Repository
@Transactional
public class UserDAOImpl implements UserDAO {

@Autowired
private SessionFactory sessionFactory;

protected SessionFactory getSessionFactory() {
    try {
        return (SessionFactory) new InitialContext().lookup("SessionFactory");
    } catch (Exception e) {
        log.error("Could not locate SessionFactory in JNDI", e);
        throw new IllegalStateException("Could not locate SessionFactory in JNDI");
    }
}

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
public Set<Client> getClients() {
    return this.clients;
}

......
}

客户端中,我设置:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
public User getUser() {
    return this.user;
}

SessionFactoryroot-context.xml 中定义。这样,我应该能够从分离的 User 对象中获取 clients,对吧?但是,当我运行此代码时:

results.addAll(userDAO.findById(id).getClients());

它返回了以下异常:

WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: com.hersbitcloud.cancercloud.models.Client["user"]->com.hersbitcloud.cancercloud.models.User["clientss"]->org.hibernate.collection.internal.PersistentSet[0]->com.hersbitcloud.cancercloud.models.Client["user"]->com.hersbitcloud.cancercloud.models.User["clients"]->org.hibernate.collection.internal.PersistentSet[0]-
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

堆栈跟踪非常长,我认为这意味着当我获取User时,它会同时获取Client,因为它是EAGER。然后User对象被再次获取作为Client的内部对象,即使它被设置为LAZY。这个过程周而复始,永不停息。

我知道LAZY仅在 session 中获取内容。我的问题是,为什么 User 的 session 从未过期?

最佳答案

这是因为你的模型(实体)具有双向映射。 当 Jackson 尝试序列化对象时,它面临 user.getClients()[0].getUser().getClients().... 递归链。因为你直接使用表示层上的实体。

你可以做一些事情。

  1. 使用 DTO
  2. 直接在您的实体上使用 @JsonIgnore(我不喜欢 DAO/MVC 混合)
  3. 可能有更多选择

这个answer有更好的方法来做到这一点

关于java - Hibernate HttpMessageNotWritableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830724/

相关文章:

java - Hibernate多对一属性在通过id持久化时为null

java - 暂停计时器然后继续

java - 我可以将 Slice 与 findAll 方法一起使用吗 : Spring Data

java - 在许多类中使用 spring applicationContext

java - 在 Spring 与 BoneCP : "Database access prob lem. Killing off this connection..." 进行预定操作时连接断开

java - 将 PostgreSQL JSON 列映射到 Hibernate 实体属性

时间之前的 Java 日期在生产中无法按预期工作

java - SocketChannel 还没有准备好

java - 如何让 Kotlin 停止将参数转换到错误的类(接口(interface))

java - Spring 中的表单处理