How to configure Spring without persistence.xml?

From Spring Guide Accessing Data with JPA

@Configuration
@EnableJpaRepositories
public class Application {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder().setType(H2).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
        lef.setDataSource(dataSource);
        lef.setJpaVendorAdapter(jpaVendorAdapter);
        lef.setPackagesToScan("hello");
        return lef;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setShowSql(false);
        hibernateJpaVendorAdapter.setGenerateDdl(true);
        hibernateJpaVendorAdapter.setDatabase(Database.H2);
        return hibernateJpaVendorAdapter;
    }

Spring Boot

With Spring Boot enabled application this is even easier:

Sample application.yaml

spring:
    datasource:
        url: jdbc:h2:mem:test
        username: sa
        password: sa
        driver-class-name: org.h2.Driver
    jpa:
        database: H2
        show-sql: false
        hibernate:
            format_sql: true
            ddl-auto: auto

Leave a Comment