SpringBoot2 JPA解决懒加载异常

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 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 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;
    }

}

我大概实现了一下,具体的如果大佬找到更好的方法或者发现我的方法是错的,希望各位大佬提醒一下!感谢!

你可能感兴趣的:(SpringBoot,java,SpringBoot2,技术点总结)