java - hibernate 和 jackson (java.lang.IllegalStateException : Cannot call sendError() after the response has been committed)

标签 java json hibernate orm jackson

您好,Hibernate 和 Jackson 有问题。有两个 POJO

@Entity
@Table(name = "USERS")
public class User implements Serializable {
static final long serialVersionUID = 4235637833262722256L;

@Id
@GeneratedValue
private int id;

@Column(name = "CREATION_DATE")
private Date creationDate;

@Column(name = "FIRST_NAME")
private String firstName;

@Column(name = "LAST_NAME")
private String lastName;

@Version
@Column(name = "VERSION")
private int version;

@Column(name = "E_MAIL")
private String email;

@Column(name = "ENABLED")
private boolean enabled;

@Column(name = "LOGIN")
private String login;

@Column(name = "PASSWORD")
private String password;

@JsonManagedReference("role")
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Set<UserRole> userRole;

为 Spring 安全集成创建的用户及其角色。

@Entity
@Table(name = "USER_ROLES")
public class UserRole {

@Version
@Column(name = "VERSION")
int version;
@Id
@GeneratedValue
private int id;

@JsonBackReference("role")
@ManyToOne()
@JoinColumn(name = "USER_ID", referencedColumnName = "ID")
private User user;

@Column(name = "ROLE")
private String role;

并且有一个 Controller ,它通过 Jackson 由用户 Json 制作。用方法

  @RequestMapping(value = "/login", method = RequestMethod.GET, produces = "application/json")
private @ResponseBody User checkLoginAvailability(@RequestParam String login) {
    User user = appContext.getUserService().readUserByLogin(login);
    if (user != null) {
        return user;
    }
    return new User();
}

当此方法返回没有空字段的用户时,它会抛出:

26-Oct-2014 14:31:17.652 WARNING [http-nio-8080-exec-4] 
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.doResolveException 
Handling of [org.springframework.http.converter.HttpMessageNotWritableException]
resulted Exception java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

当我添加 @OneToMany(mappedBy = "user", cascade = CascadeType.ALL,fetch = FetchType.EAGER) 时出现了问题,之前它只是 fetch = FetchType.EAGER,但我无法保存用户在这种情况下,由于他的角色,表 USER_ROLE 是空的。我在 jackson 某处的无限循环中解决了这个问题,添加了一些注释 @JsonBackReference("role") 和 @JsonManagedReference("role") 但没有任何改变。我怎么解决这个问题?谢谢!

最佳答案

我建议在导致循环引用的属性上添加 @jsonignore。这将告诉 jackson 不要序列化该属性。

关于java - hibernate 和 jackson (java.lang.IllegalStateException : Cannot call sendError() after the response has been committed),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26572245/

相关文章:

java - 这种声明的类型是什么?

java - 集合与数组性能明智

json - Visual Studio 对 JSON 属性排序错误

java - Hibernate 的一级缓存不适用于 boolean 类型?

JavaFX编程ActionHandler

java - 从 ComponentColorModel 获取 RGB 分量

javascript - 数据表的省略号渲染

json - Play 2.1-RC2 : Read keys from JSON

java, hibernate : mapping property with a query

spring - 无法转换为 org.hibernate.annotations.common.reflection.MetadataProviderInjector