hibernate+spring mvc, 解决hibernate 对象懒加载 json序列化问题

时间:2023-03-09 09:53:08
hibernate+spring mvc,  解决hibernate 对象懒加载 json序列化问题

引用地址

在使用Spring MVC时,@ResponseBody 注解的方法返回一个有懒加载对象的时候出现了异常,以登录为例:

  1. @RequestMapping("login")
  2. @ResponseBody
  3. public Object login(@RequestParam String username,@RequestParam String password){
  4. List<User> list=userDAO.findByUsername(username);
  5. if(list.size()>0){
  6. User user=list.get(0);
  7. if(user.getPassword().equals(password)){
  8. return new Result(user, "操作成功", true);
  9. }else{
  10. return new Result(null, "密码错误", true);
  11. }
  12. }else{
  13. return new Result(null, "用户未注册", false);
  14. }
  15. }

客户端抛出org.hibernate.LazyInitializationException异常。通过查询资料和摸索整理出三种解决方法:

第一种:(推荐)

在web.xml中加入:

  1. <filter>
  2. <filter-name>openSession</filter-name>
  3. <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  4. <init-param>
  5. <param-name>singleSession</param-name>
  6. <param-value>false</param-value>
  7. </init-param>
  8. </filter>
  9. <filter-mapping>
  10. <filter-name>openSession</filter-name>
  11. <url-pattern>/*</url-pattern>
  12. </filter-mapping>

这样返回的Spring mvc返回的Json串也包含一对多关系中的对象,不过都是空的。

  1. {"message":"操作成功","results":{"language":null,"id":"402881e6421e40b601421e4111c60001","type":null,"extra":null,"time":null,"username":"wanggang","msg":null,"password":"138333","tag":null,"tel":null,"qq":null,"email":null,"gender":null,"lat":null,"lang":null,"point":null,"openid":null,"city":null,"photo":null,"notes":[],"chatsForUserTwoId":[],"attentionsForUserId":[],"attentionsForAttentionUserId":[],"logs":[],"chatsForUserOneId":[],"commentsForNoteId":[],"commentsForUserId":[]},"success":true}

第二种方法(推荐):

在一对多的关系中加@JsonIgnore,这样Jackson在转换的时候就会过滤掉这个对象:

  1. @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
  2. @JsonIgnore
  3. public Set<Log> getLogs() {
  4. return this.logs;
  5. }
  6. public void setLogs(Set<Log> logs) {
  7. this.logs = logs;
  8. }

第三种方式:

把fetch模式配置成“FetchType.EAGER”,这样的方式可以解决问题,但是这样的方式会强制提取一对多关系中的数据,生成很多无用数据,也会增加系统负担,所以不建议采用。

  1. @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
  2. public Set<Log> getLogs() {
  3. return this.logs;
  4. }
  5. public void setLogs(Set<Log> logs) {
  6. this.logs = logs;
  7. }

其实还有一种方法,就是jsonignore注解方法