如何在SpringBoot2項目中利用JPA解決懶加載異常的問題?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
站在用戶的角度思考問題,與客戶深入溝通,找到泰州網(wǎng)站設計與泰州網(wǎng)站推廣的解決方案,憑借多年的經驗,讓設計與互聯(lián)網(wǎng)技術結合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都網(wǎng)站制作、成都網(wǎng)站設計、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、域名注冊、網(wǎng)絡空間、企業(yè)郵箱。業(yè)務覆蓋泰州地區(qū)。@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 PageshowPage(@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 showSortPage(@RequestParam(value = "page") Integer page, @RequestParam(value = "size") Integer size){ System.out.println("排序分頁: page:"+page+"; size:"+size); Page list = employeeService.getPageSort(page, size); Iterator it=list.iterator(); while(it.hasNext()){ System.out.println("value:"+(it.next()).getDepartment().getDeptName()); } return list; } }
我大概實現(xiàn)了一下,具體的如果大佬找到更好的方法或者發(fā)現(xiàn)我的方法是錯的,希望各位大佬提醒一下!感謝!
補充: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(); }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)網(wǎng)站建設公司,的支持。