hibernate+spring mvc, 解决hibernate 对象懒加载 json序列化问题
在使用Spring MVC时,@ResponseBody 注解的方法返回一个有懒加载对象的时候出现了异常,以登录为例:
- @RequestMapping("login")
- @ResponseBody
- public Object login(@RequestParam String username,@RequestParam String password){
- List<User> list=userDAO.findByUsername(username);
- if(list.size()>0){
- User user=list.get(0);
- if(user.getPassword().equals(password)){
- return new Result(user, "操作成功", true);
- }else{
- return new Result(null, "密码错误", true);
- }
- }else{
- return new Result(null, "用户未注册", false);
- }
- }
客户端抛出org.hibernate.LazyInitializationException异常。通过查询资料和摸索整理出三种解决方法:
第一种:(推荐)
在web.xml中加入:
- <filter>
- <filter-name>openSession</filter-name>
- <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
- <init-param>
- <param-name>singleSession</param-name>
- <param-value>false</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>openSession</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
这样返回的Spring mvc返回的Json串也包含一对多关系中的对象,不过都是空的。
- {"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在转换的时候就会过滤掉这个对象:
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
- @JsonIgnore
- public Set<Log> getLogs() {
- return this.logs;
- }
- public void setLogs(Set<Log> logs) {
- this.logs = logs;
- }
第三种方式:
把fetch模式配置成“FetchType.EAGER”,这样的方式可以解决问题,但是这样的方式会强制提取一对多关系中的数据,生成很多无用数据,也会增加系统负担,所以不建议采用。
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
- public Set<Log> getLogs() {
- return this.logs;
- }
- public void setLogs(Set<Log> logs) {
- this.logs = logs;
- }
其实还有一种方法,就是jsonignore注解方法