Jak skonfigurować Spring bez uporczywości.xml?

Próbuję skonfigurować konfigurację spring xml bez konieczności tworzenia dodatkowego persistence.xml. Ale ciągle dostaję następujący wyjątek, mimo że włączyłem właściwości bazy danych w spring.xml

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\Users\me\workspace\app\src\main\webapp\WEB-INF\applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: No persistence units parsed from {classpath*:META-INF/persistence.xml}
Wiosna.xml:
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
  </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
     <property name="jpaProperties">
         <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
         </props>
      </property>
    </bean>
Co mi umyka?
Author: Vlad Mihalcea, 2014-01-27

4 answers

Określ właściwości "packagesToScan" & "persistenceUnitName" w definicji entityManagerFactory bean.

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <property name="persistenceUnitName" value="myPersistenceUnit" />
        <property name="packagesToScan" >
            <list>
                <value>org.mypackage.*.model</value>
            </list>
        </property>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            </props>
        </property>
    </bean>

Zauważ, że jest to wersja Wiosenna > 3.1

 28
Author: Zaki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-27 13:46:43

Z Spring Guide Dostęp do danych za pomocą 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

Z włączoną aplikacją Spring Boot jest to jeszcze łatwiejsze:

Próbka 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
 40
Author: MariuszS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-30 09:16:01

Odpowiedź Mariusza jest dobra z tym wyjątkiem, że metoda entityManagerFactory powinna zwracać EntityManagerFactory. Aby to zrobić można napisać tak:

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

Dla przyszłych odbiorców: poniżej pracował kod:

@Bean (name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter)
{
    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
    lef.setDataSource(dataSource);
    lef.setJpaVendorAdapter(jpaVendorAdapter);
    lef.setPackagesToScan("*.models*");
    lef.afterPropertiesSet(); // It will initialize EntityManagerFactory object otherwise below will return null
    return lef.getObject();
}
 3
Author: Mustafa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-05 19:55:06

Zakładając, że masz implementację PersistenceProvider (np. org.hibernate.jpa.HibernatePersistenceProvider), możesz użyć metody PersistenceProvider#createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map), aby uruchomić EntityManagerFactory bez potrzeby stosowania persistence.xml.

Jednak denerwujące jest to, że musisz zaimplementować interfejs PersistenceUnitInfo, więc lepiej będzie użyć Springa lub Hibernate, które obsługują bootstrapowanie JPA bez Pliku persistence.xml:

this.nativeEntityManagerFactory = provider.createContainerEntityManagerFactory(
    this.persistenceUnitInfo, 
    getJpaPropertyMap()
);

Gdzie PersistenceUnitInfo jest zaimplementowana przez specyficzną dla Springa klasę MutablePersistenceUnitInfo .

Sprawdź ten artykuł aby zobaczyć, jak możesz osiągnąć ten cel za pomocą Hibernate.

 2
Author: Vlad Mihalcea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-05 17:29:25