您好,登錄后才能下訂單哦!
如何在SpringBoot2項目中利用JPA解決懶加載異常的問題?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
@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; } }
我大概實現(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(); }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。