您好,登錄后才能下訂單哦!
如何在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(); }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。