欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-09-06 17:16:08
jpa解决懒加载异常在我上一遍文章上进行行修改,springboot2 实现jpa分页和排序分页实体类上改:@entity@table(name = "employee")@jsonignorepro...

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;
@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();
 }

成功解决~

总结:

要解决no session 问题需要:

配置文件中加jpa.properties.open-in-view: true同时在启动文件中加@bean

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