How to configure Spring without persistence.xml?

后端 未结 4 1876
礼貌的吻别
礼貌的吻别 2020-12-13 05:07

I\'m trying to set up spring xml configuration without having to create a futher persistence.xml. But I\'m constantly getting the following exception, even thou

4条回答
  •  借酒劲吻你
    2020-12-13 05:25

    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
    

提交回复
热议问题