例如,我有2个班级。首先
@Entity
@Table(name = "employee")
public class Employee implements Serializable{
@ManyToOne
@JoinColumn(name = "office_address_id")
private Address address;
//setters and getters
}
第二个:
@Entity
@Table(name = "address")
public class Address implements Serializable{
@OneToMany(mappedBy = "address")
private List<Employee> employeeList;
//setters and getters
}
因此,如果我要从数据库中读取
Employee
,则会读取address
字段。 Address
具有带有LazyInitializingException的employeeList
。但是我不想知道employeeList
。我只想知道employee.getAddress()
。我想发送JSON对象
Employee
。但是在客户端,由于LazyInitializingException而有Failed to load resource: the server responded with a status of 500 (Internal Server Error)
。我可以使用:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="myPersistenceUnit"/>
<property name="packagesToScan" value="com.itechart.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="showSql" value="false"/>
<property name="generateDdl" value="true"/>
</bean>
</property>
<!-- USE--!>
<property name="jpaProperties">
<props>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
<!-- END USE--!>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
</property>
</bean>
最佳答案
JSON
会话关闭后,您的Address.employeeList
映射器可能会访问hibernate
。这就是为什么它发送LazyInitializingException
的原因。
您可以尝试以下任何一种解决方案来解决该问题。
1)从employeeList
映射中排除JSON
在Jackson
中,我们可以添加@JsonIgnore
@JsonIgnore
public List<Employee> getEmployeeList() {
}
2)初始化
employeeList
,然后将其发送到JSON
映射器。您可以通过调用
employeeList.size()
方法来实现3)您可以将fetchType更改为eager,如下所示
@OneToMany(mappedBy = "address", fetch = FetchType.EAGER)
private List<Employee> employeeList;