2016-02-28 1 views
0

Je voudrais obtenir une confirmation sur la requête "Y at-il un moyen de configurer la configuration de la base de données via database.properties en utilisant persistance.xml". Le ci-dessous est-il possible?comment configurer la base de données configurable du fichier persistance.xml via le fichier database.properties

Ma configuration suivante fonctionne tout à fait bien,

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> 
    <persistence-unit name="spring-data-jpa-krishna" transaction-type="RESOURCE_LOCAL"> 
     <class>net.javabeat.springdata.model.Address</class> 
     <class>net.javabeat.springdata.model.Employee</class> 

     <properties> 
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" /> 
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> 
      <property name="javax.persistence.jdbc.user" value="root" /> 
      <property name="javax.persistence.jdbc.password" value="root" /> 

      <property name="hibernate.show_sql" value="true" /> 
      <property name="eclipselink.logging.level" value="FINE" /> 
      <property name="eclipselink.ddl-generation" value="create-tables" /> 
     </properties> 
    </persistence-unit> 
</persistence> 

mais j'ai beaucoup l'environnement pour déployer les codes d'application comme Dev, QA, UAT, SAT, SystemTest etc, donc je voulais faire la configuration comme ci-dessous
database.properties:

mysql.jdbc.driver.class=com.mysql.jdbc.Driver 
mysql.jdbc.url=jdbc:mysql://localhost:3306/test 
mysql.jdbc.username=root 
mysql.jdbc.password=root 
hibernate.show_sql=true 
eclipselink.logging.level=FINE 
eclipselink.ddl-generation=create-tables 

persistence.xml

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> 
    <persistence-unit name="spring-data-jpa-krishna" transaction-type="RESOURCE_LOCAL"> 
     <class>net.javabeat.springdata.model.Address</class> 
     <class>net.javabeat.springdata.model.Employee</class> 

     <properties> 
      <property name="javax.persistence.jdbc.url" value="${mysql.jdbc.url}" /> 
      <property name="javax.persistence.jdbc.driver" value="${mysql.jdbc.driver.class}" /> 
      <property name="javax.persistence.jdbc.user" value="${mysql.jdbc.username}" /> 
      <property name="javax.persistence.jdbc.password" value="${mysql.jdbc.password}" /> 

      <property name="hibernate.show_sql" value="${hibernate.show_sql}" /> 
      <property name="eclipselink.logging.level" value="${eclipselink.logging.level}" /> 
      <property name="eclipselink.ddl-generation" value="eclipselink.ddl-generation" /> 
     </properties> 
    </persistence-unit> 
</persistence> 

Cela m'aiderait à résoudre mes frais généraux. Mais je me demande comment persistece.xml chargerait database.properties afin d'obtenir placeholders correctement?

Ce lien How to externalize properties from JPAs persistence.xml? l'a fait via JNDI, mais je voulais simplement le faire via le fichier database.properties.

Edit-1: Oui, je suis en utilisant le fichier printemps-context.xml

<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 

    <!-- For consider the using of annotations foe defining Spring Bean --> 
    <context:annotation-config /> 

    <!-- For defining Spring Bean --> 
    <context:component-scan base-package="net.javabeat.springdata.beans" /> 

    <!-- For bootstrapping the Spring Repository --> 
    <jpa:repositories base-package="net.javabeat.springdata.repository" /> 

    <!-- Necessary to get the entity manager injected into the factory bean --> 
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> 

    <bean id="registrationBean" class="net.javabeat.springdata.beans.RegistrationBean" /> 


    <!-- ======= WAY-1 ========= --> 
    <!-- ===== Define EclipseLink JPA Vendor Adapter ===== --> 
    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"> 
     <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" /> 
     <property name="generateDdl" value="false" /> 
     <property name="showSql" value="true" /> 
    </bean> 

    <!-- Entity Manager Factory --> 
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> 
     =========== Read persistent.xml file from here =========== 
     <property name="persistenceUnitName" value="spring-data-jpa-krishna" /> 
     <property name="jpaVendorAdapter" ref="jpaVendorAdapter" /> 
     <!-- spring based scanning for entity classes--> 
     <property name="packagesToScan" value="net.javabeat.springdata.*" /> 
    </bean> 

    <!-- Transaction Manager --> 
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
     <property name="entityManagerFactory" ref="entityManagerFactory" /> 
    </bean> 

    <!-- Enable Transactional Manner --> 
    <tx:annotation-driven transaction-manager="transactionManager" /> 

</beans> 

Edit-1: Je vois ci-dessous erreur maintenant:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.javabeat.springdata.repository.EmployeeRepository net.javabeat.springdata.beans.RegistrationBean.employeeRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository': Cannot create inner bean '(inner bean)#5d3c9c43' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#5d3c9c43': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [SpringContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: PersistenceProvider [[email protected]] did not return an EntityManagerFactory for name 'spring-data-jpa-krishna' 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) 
    ... 13 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository': Cannot create inner bean '(inner bean)#5d3c9c43' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#5d3c9c43': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [SpringContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: PersistenceProvider [[email protected]] did not return an EntityManagerFactory for name 'spring-data-jpa-krishna' 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:313) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1475) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1220) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) 
    ... 15 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#5d3c9c43': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [SpringContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: PersistenceProvider [[email protected]] did not return an EntityManagerFactory for name 'spring-data-jpa-krishna' 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) 
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634) 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:444) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1117) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1012) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:299) 
    ... 28 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [SpringContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: PersistenceProvider [[email protected]] did not return an EntityManagerFactory for name 'spring-data-jpa-krishna' 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1572) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) 
    ... 36 more 
Caused by: java.lang.IllegalStateException: PersistenceProvider [[email protected]] did not return an EntityManagerFactory for name 'spring-data-jpa-krishna' 
    at org.springframework.orm.jpa.LocalEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalEntityManagerFactoryBean.java:90) 
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1631) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568) 
    ... 43 more 

I a apporté des modifications dans le fichier pom.xml:

<build> 
     <pluginManagement> 
      <plugins> 
       <plugin> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-compiler-plugin</artifactId> 
        <version>3.1</version> 
        <configuration> 
         <source>${java.version}</source> 
         <target>${java.version}</target> 
        </configuration> 
       </plugin> 
      </plugins> 
     </pluginManagement> 
     <!-- <filters> 
      <filter>database.properties</filter>  
     </filters> --> 
     <resources> 
      <resource> 
       <directory>src/main/resources</directory> 
      </resource> 
     </resources> 
    </build> 

persistence.xml

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> 
    <persistence-unit name="spring-data-jpa-krishna" transaction-type="RESOURCE_LOCAL"> 
     <provider>org.hibernate.ejb.HibernatePersistence</provider> 
     <class>net.javabeat.springdata.model.Address</class> 
     <class>net.javabeat.springdata.model.Employee</class> 

     <!-- http://docs.oracle.com/cd/E16439_01/doc.1013/e13981/cfgdepds005.htm --> 
     <properties>   
      <property name="javax.persistence.jdbc.url" value="${jdbc.mysql.url}" /> 
      <property name="javax.persistence.jdbc.driver" value="${jdbc.mysql.driver.class}" /> 
      <property name="javax.persistence.jdbc.user" value="${jdbc.mysql.username}" /> 
      <property name="javax.persistence.jdbc.password" value="${jdbc.mysql.password}" /> 

      <property name="eclipselink.logging.level" value="FINE" /> 
      <property name="eclipselink.ddl-generation" value="create-tables" /> 
     </properties> 
    </persistence-unit> 
</persistence> 
+0

Si vous utilisez Spring, vous pouvez choisir d'utiliser ** NON ** 'persistence.xml' et obtenir les propriétés de' database.properties' pour configurer 'LocalContainerEntityManagerFactoryBean'. –

+0

En outre, vous avez utilisé les options spécifiques 'Eclipse Link' et' Hibernate' en même temps, pourquoi? –

+0

Ali - Oui, j'utilise le printemps, s'il vous plaît voir mes mises à jour ci-dessous et le fichier spring-Context.xml. Les options spécifiques à Hibernate peuvent ne pas être pertinentes et ne pas être utilisées, la configuration ci-dessus est la preuve –

Répondre

1

Lorsque vous utilisez Spring, vous pouvez choisir de ne pas utiliser du tout persistence.xml et configurer le EntityManagerFactory par un FactoryBean nommé LocalContainerEntityManagerFactoryBean. Ce answer peut vous donner une idée sur la façon de configurer un LocalContainerEntityManagerFactoryBean.

Si vous insistez à utiliser persistence.xml, vous pouvez ajouter les ${...} espaces réservés dans votre persistence.xml et l'utilisation, par exemple, le filtrage des ressources de Maven pour alimenter les valeurs réelles. Avec cette approche, vous devez définir les propriétés comme propriétés Maven et vous n'aurez pas besoin d'un database.properties distinct. Dans cette approche, vous devez ajouter les propriétés que les propriétés de Maven, quelque chose comme ce qui suit:

<properties> 
    <mysql.jdbc.driver.class>com.mysql.jdbc.Driver</<mysql.jdbc.driver.class> 
    <mysql.jdbc.url>jdbc:mysql://localhost:3306/test</mysql.jdbc.url> 
    <mysql.jdbc.username>root</mysql.jdbc.username> 
    <mysql.jdbc.password>root</mysql.jdbc.password> 
    <hibernate.show_sql>true</hibernate.show_sql> 

    <!-- You've got to be kidding me! --> 
    <eclipselink.logging.level>FINE</eclipselink.logging.level> 
    <eclipselink.ddl-generation>create-tables</eclipselink.ddl-generation> 
</properties> 

Et en ajoutant ces derniers à votre section de construction en pom.xml:

<build> 
    <resources> 
     <resource> 
      <directory>src/main/resources</directory> 
     </resource> 
    </resources> 
</build> 

Chaque espace réservé avec ${...} syntaxe dans vos ressources dans src/main/resources seront remplacés par leur valeur réelle, à savoir ceux qui sont définis dans la section properties dans pom.xml.

+0

Ali - Merci beaucoup pour cela, s'il vous plaît voir mes mises à jour Edit-1 –

+0

Vous devriez ajouter ces 'properties' dans votre' pom.xml' –

+0

Pourriez-vous s'il vous plaît jeter un oeil à mon code de https://github.com/ test512/printemps-données-jpa-krishna? Ca ne marche pas pour moi –