SpringBoot2 JPA解決懶加載異常的問題
jpa解決懶加載異常
在我上一遍文章上進行行修改,SpringBoot2 實現JPA分頁和排序分頁
實體類上改:
@Entity @Table(name = "employee") @JsonIgnoreProperties(value={"hibernateLazyInitializer", "department"}) public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer empId; private String lastName; private String email; @Temporal(TemporalType.DATE) private Date birth; @Temporal(TemporalType.TIMESTAMP) private Date createTime; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "dept_id") private Department department; public Integer getEmpId() { return empId; } public void setEmpId(Integer empId) { this.empId = empId; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
控制器驗證
import java.util.Iterator; @RestController public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping("/emp") public Page<Employee> showPage(@RequestParam(value = "page") Integer page, @RequestParam(value = "size") Integer size){ System.out.println("分頁: page:"+page+"; size:"+size); return employeeService.getPage(page, size); } @GetMapping("/emp_sort") public Page<Employee> showSortPage(@RequestParam(value = "page") Integer page, @RequestParam(value = "size") Integer size){ System.out.println("排序分頁: page:"+page+"; size:"+size); Page<Employee> list = employeeService.getPageSort(page, size); Iterator<Employee> it=list.iterator(); while(it.hasNext()){ System.out.println("value:"+(it.next()).getDepartment().getDeptName()); } return list; } }
我大概實現瞭一下,具體的如果大佬找到更好的方法或者發現我的方法是錯的,希望各位大佬提醒一下!感謝!
補充:SpringBoot jpa 使用懶加載時,報異常:session失效
報異常:
could not initialize proxy – no Session
1、在方法上加@Transactional 註解,失敗
2、在application.yml 文件加上jpa.properties.open-in-view: true 失敗
3、在ResourceServerApplication.java 啟動文件中加上:
@Bean public OpenEntityManagerInViewFilter openEntityManagerInViewFilter() { return new OpenEntityManagerInViewFilter(); }
成功解決~
總結:
要解決no session 問題需要:
配置文件中加jpa.properties.open-in-view: true同時在啟動文件中加@Bean
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。
推薦閱讀:
- SpringBoot2 實現JPA分頁和排序分頁的案例
- SpringMVC RESTFul實體類創建及環境搭建
- Java 實戰范例之員工管理系統的實現
- SpringBoot模擬員工數據庫並實現增刪改查操作
- Mybatis聯合查詢的實現方法