SpringBoot2 JPA解决懒加载异常的问题

时间:2021-05-20

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;@RestControllerpublic 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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章