例如,我有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;

08-05 07:28