简体   繁体   中英

Obtaining Hibernate Session with Spring JPA

I can't seem to get my Spring JPA config working correctly. I have a Spring REST service. If I set all the entities to FetchType.EAGER , everything works as expected. But I don't want to do that for the obvious reasons.

When I set my entities to FetchType.LAZY , I get the following error:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.service.entities.MyEntity.lawfirmCaseDecisions, could not initialize proxy - no Session

I've looked through other similar SO questions but my still running into the same issue. Here's my config:

@Configuration
@Import(EnvironmentProvider.class)
@EnableTransactionManagement
@Slf4j
public class DataSourceProvider {

    @Autowired EnvironmentProvider envProvider;

    @Bean
    DataSource dataSource() {

        final EnvConfig env = envProvider.envConfig();

        MysqlDataSource dataSource = new MysqlDataSource();    
        dataSource.setUrl(env.findProperty("db.url"));
        dataSource.setPortNumber( Integer.parseInt(env.findProperty("db.port")) );
        dataSource.setUser(env.findProperty("db.username"));
        dataSource.setPassword(env.findProperty("db.password"));
        return dataSource;
    }

    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory() {

        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPackagesToScan("com.offtherecord.service.core.entities");
        //entityManagerFactoryBean.setPersistenceUnitName("OTR");   

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(va);

        Properties ps = new Properties();
        ps.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        // ps.put("hibernate.show_sql", "true"); //useful for debugging
        ps.put("hibernate.format_sql", "true");

        entityManagerFactoryBean.setJpaProperties(ps);
        return entityManagerFactoryBean;
    }

    @Bean
    @PersistenceContext
    JpaTransactionManager transactionManager() {

        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().nativeEntityManagerFactory);
        return transactionManager;
    }
}

For quick testing, I added the @Transactional annotation on my controller method. In the below code, the UserEntity class has a list of Orders which doesn't get populated:

@RequestMapping(method = RequestMethod.GET)
@Transactional
public ResponseEntity<GetOrdersResponse> getOrders() {

    UserEntity activeUser = controllerUtil.getActiveUser();
    ...
    return new ResponseEntity<>(new GetOrdersResponse(), HttpStatus.OK);
}

I'd love to get past this!

You need to use the method as such referenced from here.

    @Entity
@NamedEntityGraph(name = "GroupInfo.detail",
  attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {

  // default fetch mode is lazy.
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  …
}

Example 48. Referencing a named entity graph definition on an repository query method.

@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}

In this above example you need to mark the members in that particular method in which you want to load a particular association eagerly. in the above example it is "members" feild.

Generally speaking, all the associations are marked lazy and the ones which you want to fetch as case demands can be fetched, such speacial methods can be created. Example, let say you have a screen in which there are all details of the customer, so in such a VIEW you would have acustom method which loads all the addresses of the customer eagerly, where as for other views, this addresses can be kept lazy and something else can be loaded eagerly.

Surely Works, thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM