Hibernate dialect issue with Spring configuration - java

I use Hibernate (through JPA) configured by Spring and when I launch my application (war deployed on Tomcat 6), I get this error:
org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
It seems strange because I've set the hibernate dialect as follows:
p:databasePlatform="org.hibernate.dialect.MySQL5Dialect
For more information, here my full applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost/room_management" p:username="root" p:password=""/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:persistenceUnitName="RoomManagement">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="MYSQL"
p:databasePlatform="org.hibernate.dialect.MySQL5Dialect"
p:showSql="true"/>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<context:annotation-config/>
<context:component-scan base-package="com.parisdescartes.roommanagement.*"/>
<tx:annotation-driven/>
</beans>
So, I decided to precise Hibernate Dialect within META-INF/persistence.xml file, and this time that works. Here how I precised it:
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL5Dialect"/>
</properties>
Do you have an idea why Hibernate Dialect is not set using Spring configuration ?

Not sure why it won't work with your configuration. Maybe something goes wrong with using the p: annotation. I'll post my code (which works for my config) to try if it will fix your code! :)
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
</property>
</bean>
Good luck!

A bit late, but I think this could add value. Not necessarily you need to add databasePlatform property if you specify database property, the adapter itself will figure out the dialect.
<property name="database" value="MYSQL" />
Relevant code from org.springframework.orm.jpa.vendor.HibernateJPAVendorAdapter
protected Class determineDatabaseDialectClass(Database database) {
switch (database) {
case DB2: return DB2Dialect.class;
case DERBY: return DerbyDialect.class;
case H2: return H2Dialect.class;
case HSQL: return HSQLDialect.class;
case INFORMIX: return InformixDialect.class;
case MYSQL: return MySQLDialect.class;
case ORACLE: return Oracle9iDialect.class;
case POSTGRESQL: return PostgreSQLDialect.class;
case SQL_SERVER: return SQLServerDialect.class;
case SYBASE: return SybaseDialect.class;
default: return null;
}
}

Dialect could be auto-detected from DataSource driver. So nether hibernate.dialect no database were needed.
If exception 'hibernate.dialect' not set happened, it usually means, than something wrong with DB connection:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="ru.javawebinar.**.model">
<property name="jpaPropertyMap">
<map>
<entry key="#{T(org.hibernate.cfg.AvailableSettings).FORMAT_SQL}" value="${hibernate.format_sql}"/>
<entry key="#{T(org.hibernate.cfg.AvailableSettings).USE_SQL_COMMENTS}" value="${hibernate.use_sql_comments}"/>
</map>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${jpa.showSql}">
</bean>
</property>
</bean>

Related

How to configure jasypt in java spring 2.0?

I had a problem with Jasypt..
I can't configure jasypt in my program with Java Spring.
This is my configuration in jdbc.properties:
c3p0.db.driverClass = org.postgresql.Driver
c3p0.db.url = jdbc:postgresql://localhost:5432/igate-iacss
c3p0.db.user = postgres
c3p0.db.pass = ENC(5Urp3uiKn828jwkOerTslYtSSeMul0p7)
c3p0.db.initialPoolSize = 5
c3p0.db.minPoolSize = 5
c3p0.db.maxPoolSize = 20
c3p0.num.helper.thread = 5
My datasource code in 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"
default-lazy-init="false">
<!-- turn on #Resource, #PostConstruct, and #PreDestroy -->
<context:annotation-config />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>${c3p0.db.driverClass}</value>
</property>
<property name="jdbcUrl">
<value>${c3p0.db.url}</value>
</property>
<property name="user">
<value>${c3p0.db.user}</value>
</property>
<property name="password">
<value>${c3p0.db.pass}</value>
</property>
<property name="initialPoolSize">
<value>${c3p0.db.initialPoolSize}</value>
</property>
<property name="minPoolSize">
<value>${c3p0.db.minPoolSize}</value>
</property>
<property name="maxPoolSize">
<value>${c3p0.db.maxPoolSize}</value>
</property>
<property name="numHelperThreads">
<value>${c3p0.num.helper.thread}</value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
How to configure that in java spring?
Please help me.
I hope someone can help me, just stack and can't think anymore.
Please refer to the document http://www.jasypt.org/spring3.html# for integrating spring and jasypt depends upon the spring version you use.
I've created a sample spring application with jasypt. Refer to the repo here if you are looking for an example spring-jasypt-example
You may need to add mvn dependency jasypt-mvn-dependency and integrate jasypt-spring-configuration.

Trouble with Spring Data Repositories

It has been 2 days i am trying to work with Spring Data repositories and trying to setup a simple repository.
I have simple UserRepository using CrudRepository
I have my entity class
And here is my XML in which the highlighted line is giving me error in web browser
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<jpa:repositories base-package="com.mydata"/>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="test"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="com.mydata"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
</beans>
When i access the controller in which i initilize this beans class i get following error in web browser
Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.orm.jpa.vendor.Database' for property 'database'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.orm.jpa.vendor.Database] for property 'database': no matching editors or conversion strategy found
And this error occurs because of line in XML property name="database" value="test"
Shahzad
The indicated in the JavaDoc the database property takes the database type, not the name.
In general, I suggest to rather look at Spring Boot and its JPA support (find a guide here) as it svaes you from all the boilerplate configuration setup.
Did you try MYSQL database value? I think Spring should convert it implicitly to Database.MYSQL
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
Or Spring Boot bean definition
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter;
}

Hibernate saving entity not working

I am using Spring 3.2 mvc and Hibernate 4 in my project.
hibernate.cfg.xml
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="show_sql">true</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.validator.apply_to_ddl">false</property>
<property name="hibernate.validator.autoregister_listeners">false</property>
servlet-context.xml
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<security:global-method-security pre-post-annotations="enabled"/>
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.abc" />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
DaoImpl Class:
public void add(Entity entity) {
try {
this.sessionFactory.getCurrentSession().save(entity);
this.sessionFactory.getCurrentSession().flush();
} catch (Exception e) {
logger.error("Exception occured " + e);
}
}
This is my project configuration and dao impl class file.
root-context.xml
<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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.abc" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- <property name = "dataSource" ref = "dataSource"></property> -->
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="entityInterceptor" ref ="auditLogInterceptor"/>
</bean>
Issue
As of now in hibernate.cfg.xml, I have mentioned hibernate.connection.autocommit = true and in daoimpl while saving entity I need to call flush after .save .
If I remove hibernate.connection.autocommit = true and .flush from daoimpl class, I observed that .save method in daoimpl is not working, means my data is not inserting and even I cannot see insert query executed by hibernate on console.
hibernate.connection.autocommit = true should not be there in hibernate cfg xml as if I doing operation on multiple table in same transaction and if some error occurred then rollback will not happen.
I want that .save in daoimpl should work even I don't write hibernate.connection.autocommit = true in hibernate cfg xml and .flush.
I am using #Transactional annotation for transaction.
You haven't added any TransactionManager to your configuration:
Remove the following properties:
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
Add a connection pooling DataSource (DBCP2 is a much better alternative than C3P0)
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="your-oracle-driver-url"/>
<property name="username" value="your-username"/>
<property name="password" value="your-password"/>
</bean>
Now add the Sessionfactory Spring proxy:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
Add the TransactionManager bean
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Update
If you have the transaction manager set in a separate spring application context (e.g. root-context.xml), then move these lines from your web context to where the back-end context:
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.abc.service" />
<context:component-scan base-package="com.abc.dao" />
And only allow the web context to scan its own beans:
<context:component-scan base-package="com.abc.web" />
It's not good to mix the web and the back-end contexts responsibilities.
My problem solved, I just wrote the annotation #Transactional in the
#Repository
#Transactional
public class AbstractHibernateDao<T extends Serializable> {
private Class<T> clazz;
#Autowired
private SessionFactory sessionFactory;
And that solved that I couldnt Delete or Save without using Flush.

override spring batch admin to use mysql database

I am trying to use mysql database instead of default HSQL in spring batch admin. For that as per documentation
http://docs.spring.io/spring-batch-admin/reference/reference.xhtml and Using jndi datasource with spring batch admin
I copied env-context.xml to src/main/resources/META-INF/batch/override/manager/env-context.xml and changed its configuration value from
<value>classpath:batch-${ENVIRONMENT:hsql}.properties</value>
to
<value>classpath:batch-mysql.properties</value>
Below is my full configuration.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Use this to set additional properties on beans at run time -->
<bean id="placeholderProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/org/springframework/batch/admin/bootstrap/batch.properties</value>
<value>classpath:batch-default.properties</value>
<value>classpath:batch-mysql.properties</value>
</list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="order" value="1" />
</bean>
</beans>
I also tried coping data-source-context.xml to same folder and changing its configurations to mysql
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/batch" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="testWhileIdle" value="true"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Initialise the database if enabled: -->
<jdbc:initialize-database data-source="dataSource" enabled="false" ignore-failures="DROPS">
<jdbc:script location="classpath*:/org/springframework/batch/core/schema-drop-mysql.sql"/>
<jdbc:script location="classpath:/org/springframework/batch/core/schema-mysql.sql"/>
<jdbc:script location="classpath:/business-schema-mysql.sql"/>
</jdbc:initialize-database>
</beans>
But it still using hsql database? How to override default configuration to use mysql database ?
You shouldn't replace the <value>classpath:batch-${ENVIRONMENT:hsql}.properties</value>. Instead, pass in an environment variable ENVIRONMENT set to mysql. That should cause all the appropriate components to pick up the correct database. You can read more about that feature here: http://docs.spring.io/spring-batch-admin/reference/infrastructure.html#Environment_Settings
If you want to try using just annotations without any xml configurations - try this
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
It is working. My code is available here - http://github.com/sidnan/spring-batch-example.
I was able to get the connection working with above approach with below steps
First, I copied env-context.xml to src/main/resources/META-INF/batch/override/manager/env-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">`
<!-- Use this to set additional properties on beans at run time -->
<bean id="placeholderProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/org/springframework/batch/admin/bootstrap/batch.properties</value>
<value>classpath:batch-default.properties</value>
<value>classpath:batch-${ENVIRONMENT:sqlserver}.properties</value>
</list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="order" value="1" />
</bean>
</beans>
After that, put the following entries in batch-sqlserver.properties of sql server under resources as
# Default placeholders for database platform independent features
batch.remote.base.url=http://localhost:8080/spring-batch-admin-sample
# Non-platform dependent settings that you might like to change
batch.jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
batch.jdbc.url=jdbc:sqlserver://localhost;databaseName=batchrepo
batch.jdbc.user=la
batch.jdbc.password=la
atch.jdbc.testWhileIdle=true
batch.data.source.init=false
batch.jdbc.validationQuery=
batch.database.incrementer.class=org.springframework.jdbc.support.incrementer.SqlServerMaxValueIncrementer
batch.lob.handler.class=org.springframework.jdbc.support.lob.DefaultLobHandler
batch.database.incrementer.parent=columnIncrementerParent
batch.grid.size=2
batch.jdbc.pool.size=6
batch.verify.cursor.position=true
batch.isolationlevel=ISOLATION_SERIALIZABLE
batch.initializer.enabled=false
Since my tables were already created in the database, I skipped these entries:
#batch.drop.script=/org/springframework/batch/core/schema-drop-sqlserver.sql
#batch.schema.script=/org/springframework/batch/core/schema-sqlserver.sql
#batch.business.schema.script=business-schema-sqlserver.sql
Finally, with batch.initializer.enabled=false, I was finally able to make the connection.
I can monitor the job as well as lunch the new jobs in my admin application. These launched jobs also appear in the DB.

loading .properties in spring-context.xml and persistence.xml

is there a way to reference a .properties file in a spring-context.xml and a JPA persistence.xml?
I think I've seen somewhere an example of this in spring context files, though I can't remember where that was. Maybe someone knows this?
About the persistence.xml I am actually unsure if this works at all.
My aim is to change some properties between development and distribution configuration.
The idea I have currently is to replace all properties manually in the files via ant from a template config. Though there should be a better way to do this. :)
Rather than using your build to create a prod or dev version of your persistence.xml, just move all property settings
to your spring content.
My persistence.xml is
<?xml version="1.0" encoding="UTF-8"?>
<persistence
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
</persistence-unit>
</persistence>
In my spring content, i then use the PropertyPlaceholderConfigurer to read dev/prod property values and set these into the
entityManagerFactory bean
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:dev.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${datasource.driverClassName}"/>
<property name="url" value="${datasource.url}"/>
<property name="username" value="${datasource.username}"/>
<property name="password" value="${datasource.password}"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:./META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="JPAService"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.OracleDialect"/>
<property name="showSql" value="true" />
<property name="generateDdl" value="true"/>
</bean>
</property>
<property name="jpaProperties">
<!-- set extra properties here, e.g. for Hibernate: -->
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
</beans>
You can reference external property files from a Spring bean definition file using a PropertyPlaceholderConfigurer. I don't think that will work for a JPA persistence.xml, although Spring's JPA support allows you to incorporate most, if not all, the content of persistence.xml into the beans file itself, in which case it would work fine.

Categories

Resources