我總是得到異常:Hibernate的LazyInitializationException中使用Spring CrudRepository
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.knapp.vk.domain.Business.businessCategorySet, could not initialize proxy - no Session
我不希望設置取躍躍欲試。其他好的解決方案是什麼?
業務實體類:
@Entity
public class Business
{
@Id
@GeneratedValue
private int pk;
@ManyToMany
private Set<BusinessCategory> businessCategorySet = new HashSet<BusinessCategory>();
...
}
BusinessRepository接口:
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface BusinessRepository extends CrudRepository<Business, Integer>
{
}
配置:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = "com.knapp.vk.repositorynew")
@EnableTransactionManagement
public class JPAConfiguration
{
@Bean
public EntityManagerFactory entityManagerFactory() throws SQLException
{
return Persistence.createEntityManagerFactory("standardManager");
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory)
{
return entityManagerFactory.createEntityManager();
}
@Bean
public PlatformTransactionManager transactionManager() throws SQLException
{
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator()
{
return new HibernateExceptionTranslator();
}
}