SpringBoot2 JPA解决懒加载异常的问题
jpa解决懒加载异常
在我上一遍文章上进行行修改,SpringBoot2实现JPA分页和排序分页
实体类上改:
@Entity @Table(name="employee") @JsonIgnoreProperties(value={"hibernateLazyInitializer","department"}) publicclassEmployee{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) privateIntegerempId; privateStringlastName; privateStringemail; @Temporal(TemporalType.DATE) privateDatebirth; @Temporal(TemporalType.TIMESTAMP) privateDatecreateTime; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="dept_id") privateDepartmentdepartment; publicIntegergetEmpId(){ returnempId; } publicvoidsetEmpId(IntegerempId){ this.empId=empId; } publicStringgetLastName(){ returnlastName; } publicvoidsetLastName(StringlastName){ this.lastName=lastName; } publicStringgetEmail(){ returnemail; } publicvoidsetEmail(Stringemail){ this.email=email; } publicDategetBirth(){ returnbirth; } publicvoidsetBirth(Datebirth){ this.birth=birth; } publicDategetCreateTime(){ returncreateTime; } publicvoidsetCreateTime(DatecreateTime){ this.createTime=createTime; } publicDepartmentgetDepartment(){ returndepartment; } publicvoidsetDepartment(Departmentdepartment){ this.department=department; } }
控制器验证
importjava.util.Iterator; @RestController publicclassEmployeeController{ @Autowired privateEmployeeServiceemployeeService; @GetMapping("/emp") publicPageshowPage(@RequestParam(value="page")Integerpage,@RequestParam(value="size")Integersize){ System.out.println("分页:page:"+page+";size:"+size); returnemployeeService.getPage(page,size); } @GetMapping("/emp_sort") publicPage showSortPage(@RequestParam(value="page")Integerpage,@RequestParam(value="size")Integersize){ 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()); } returnlist; } }
我大概实现了一下,具体的如果大佬找到更好的方法或者发现我的方法是错的,希望各位大佬提醒一下!感谢!
补充:SpringBootjpa使用懒加载时,报异常:session失效
报异常:
couldnotinitializeproxy-noSession
1、在方法上加@Transactional注解,失败
2、在application.yml文件加上jpa.properties.open-in-view:true失败
3、在ResourceServerApplication.java启动文件中加上:
@Bean publicOpenEntityManagerInViewFilteropenEntityManagerInViewFilter(){ returnnewOpenEntityManagerInViewFilter(); }
成功解决~
总结:
要解决nosession问题需要:
配置文件中加jpa.properties.open-in-view:true同时在启动文件中加@Bean
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。