Didi Kumar
Didi Kumar

Reputation: 1

Spring Data JPA and Hibernate for creation of sessionFactory

Spring data jpa is an abstraction over Jpa and Spring data jpa by default implements Hibernate ORM . for using hibernate we create sessionFactory. but why we are not creating session factory when working with spring data JPA?

Upvotes: 0

Views: 586

Answers (1)

crizzis
crizzis

Reputation: 10726

The question mixes up a number of concepts related to Spring, Hibernate, and JPA, let me try to untangle them:

Spring data jpa is an abstraction over Jpa

In a way, I guess.

Spring data jpa by default implements Hibernate ORM

Umm, nope. Spring Data uses Hibernate as the provider for the JPA API.

for using hibernate we create sessionFactory

Well, yes and no. Hibernate can be used in two ways:

  • by interacting with its proprietary API, i.e. using SessionFactory, Session etc.
  • by interacting with the JPA API it implements, i.e. EntityManagerFactory and EntityManager

Spring Data JPA is doing the latter.

why we are not creating session factory when working with spring data JPA?

Because Spring Data requires an EntityManagerFactory. It does not use SessionFactory.

In Spring, this usually means you need to configure a LocalContainerEntityManagerFactoryBean. When using Spring Boot, this is done for you automatically - see here:

    @Bean
    @Primary
    @ConditionalOnMissingBean({ LocalContainerEntityManagerFactoryBean.class, EntityManagerFactory.class })
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder factoryBuilder) {
        Map<String, Object> vendorProperties = getVendorProperties();
        customizeVendorProperties(vendorProperties);
        return factoryBuilder.dataSource(this.dataSource).packages(getPackagesToScan()).properties(vendorProperties)
                .mappingResources(getMappingResources()).jta(isJta()).build();
    }

What the @ConditionalOnMissingBean({ LocalContainerEntityManagerFactoryBean.class, EntityManagerFactory.class }) annotation does is it creates a LocalContainerEntityManagerFactoryBean only if you haven't provided such a bean yourself. This means you can provide your own LocalContainerEntityManagerFactoryBean and it will be used instead, if you want.

Also, if you were to use Spring Data JPA without Spring Boot, you would have to provide a LocalContainerEntityManagerFactoryBean yourself or else Spring Data wouldn't work.

Upvotes: 1

Related Questions