2014-10-22 2 views
0

예를 들어, 나는 2 개의 클래스가 있습니다. 첫 번째최대 절전 모드 LazyInitializingException

@Entity 
@Table(name = "employee") 
public class Employee implements Serializable{ 

    @ManyToOne 
    @JoinColumn(name = "office_address_id") 
    private Address address; 

    //setters and getters 
} 

그리고 두 번째 : 나는 데이터베이스에서 Employee 읽기, 막대 그렇다면

@Entity 
@Table(name = "address") 
public class Address implements Serializable{ 

    @OneToMany(mappedBy = "address") 
    private List<Employee> employeeList; 

    //setters and getters 
} 

, 나는 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> 
+0

모두 같은 이름을 아래처럼 열망에 fetchType을 변경하고 같은 테이블에 매핑 할 수 있습니다를 호출하여 작업을 수행 할 수 있습니다. 그 맞습니까? –

+0

@sam_eera! 오, 미안해! 나는 정확하다. – TestUser

+0

"Address have employeeList with LazyInitializingException"이란 무엇을 의미 하는가? 주소의 employeeList가 지연 초기화되었다는 것을 의미 했습니까? –

답변

0

문제는 JSON 매핑 중에 모든 속성을 통해 안내합니다 및 액세스 Address.employeeList하려고한다는 것입니다. 그것은 당신이 obviuosly 더 이상 Hibernate Session에 존재하지 않으므로 예외적입니다.

중 하나를 JSON 매핑에서 employeeList (클린 솔루션)을 제외하거나 세션 전에 employeeList을 초기화는 EAGEROneToMany의 가져 오기 유형을 변경 또는 명시 적으로 (= 신속하고 더러운) 컬렉션을 초기화하여 종료됩니다.

이 같은 문제를 피하기 위해 내가 선호하는 해결책은 엔티티를 프론트 엔드 코드로 전달하지 않고 항상 TO (전송 객체)에 매핑하는 것입니다.

1

JSON 매퍼가 hibernate 세션이 닫힌 후에 Address.employeeList에 액세스 할 수 있습니다. 그것이 LazyInitializingException을 보내는 이유입니다.

아래 해결 방법 중 하나를 시도해보십시오.

1)이 전에 JSON 매퍼로 보내 employeeList 초기화) @JsonIgnore

@JsonIgnore 
public List<Employee> getEmployeeList() { 
} 

이 추가 Jackson에서 JSON 매핑

에서 employeeList을 우리가 할 수있는 제외합니다.

당신은 employeeList.size() 방법

3) 당신은 당신의 클래스의

@OneToMany(mappedBy = "address", fetch = FetchType.EAGER) 
private List<Employee> employeeList; 
+0

편집 : 죄송합니다. 다른 프레임 워크로 착각합니다. –