解决No Session错误
这里我们有Employee和Department两个类,分别配置了关系
@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer gender;
private String email;
private String phone;
private BigDecimal salary;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", gender=" + gender +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", salary=" + salary +
'}';
}
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Department {
@Id
@GeneratedValue
private Long id;
private String name;
public Department() {}
public Department(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
启动tomcat访问页面报No Session错误,原因是在懒加载加载数据时,EntityManager已经关闭
可以EntityManager对象的作用域扩大,将创建EntityManager对象的时机提前到Controller层,将关闭EntityManager对象的延后到
Controller层来解决这个错误。
具体方法:
<!-- 解决No Session错误 --> <filter> <filter-name>OpenEntityManagerInViewFilter</filter-name> <filter- class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter- class> </filter> <filter-mapping> <filter-name>OpenEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
解决No Serializer错误
当进行上面操作后,重启tomcat服务器再次访问,会报No Serializer错误,这个错误出现的原因还是由懒加载引起的:在我们调用用employee.getDepartment()的时候,实际上返回的对象是Department类的子类对象,JPA底层在实现这个懒加载原理的时候,不但在子类中重写了父类的所有属性的get方法,而且还额外添加了三个字段(“hibernateLazyInitializer”,“handler”,“fieldHandler”),但是这三个字段并没有添加get方法.
No Serializer其实就是找不到字段的get方法
j解决方法:
在懒加载字段上面添加注解
@JsonIgnoreProperties({“hibernateLazyInitializer”,“handler”,“fieldHandler”})