在使用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;
- }