IllegalArgumentException: Not an managed type - spring

I am using Spring Data with Hibernate and mongo db. I am encountering the following stack while trying to deploy my webapp into Wildfly 10.
Caused by: java.lang.IllegalArgumentException: Not an managed type:
class class com.olp.jpa.domain.docu.product.ProductTemplateBean at
org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
at
org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.(JpaMetamodelEntityInformation.java:68)
at
org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
at
org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:149)
at
org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:88)
at
org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:68)
at
org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:159)
at
org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at
org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at
org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 35 more
The code runs fine when tested in Junit using SpringJUnit4ClassRunner. Only during Wildfly deployment, I get this error. Snippets from various artifacts below:
web.xml
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Spring config
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
<context:component-scan base-package="com.olp"/>
<tx:annotation-driven />
<jpa:repositories base-package="com.olp.jpa.domain" entity-manager-factory-ref="entityManagerFactory"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitMgr"/>
<property name="jpaDialect" ref="jpaDialect"/>
<property name="jpaVendorAdapter" ref="ogmVendorAdapter"/>
</bean>
<bean id="persistenceUnitMgr" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceUnitPostProcessors">
<array>
<ref bean="persistencePostProcessor"/>
</array>
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence_olp.xml"/>
<property name="defaultPersistenceUnitName" value="productHub"/>
<property name="packagesToScan" value="com.olp.jpa.domain.docu" />
</bean>
<bean id="persistencePostProcessor" class="com.olp.jpa.OlpPersistenceUnitPostProcessor"/>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
<bean id="ogmVendorAdapter" class="com.olp.jpa.OlpHibernateOgmVendorAdapter"/>
JPA conf (persistence_olp.xml)
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
org.hibernate.ogm.jpa.HibernateOgmPersistence
ENABLE_SELECTIVE
<properties>
<!--
All other hibernate / mongo properties are externalized and provided by persistence unit post-processor in Spring
-->
<property name="jboss.as.jpa.managed" value="false" />
</properties>
Entity throwing exception (ProductTemplateBean.java)
package com.olp.jpa.domain.docu.product;
#Entity
#Table(name="phub_product_template")
public class ProductTemplateBean implements Serializable {
#Id
#DocumentId
#GeneratedValue(strategy = GenerationType.AUTO)
//#Type(type = "objectid")
private Long id;
// Omitting other fields & getters setters for brevity
}
Wildfly class loader conf ( jboss-deployment-structure.xml )
<exclusions>
<module name="org.hibernate"/>
<module name="org.hibernate.search.orm"/>
<module name="org.hibernate.search.engine"/>
<module name="org.hibernate.validator"/>
<module name="org.codehaus"/>
<module name="resteasy" />
</exclusions>
</deployment>
I would really appreciate if someone can throw some pointers. I have already read through some of the related articles, most of which point to "packagesToScan" property. This is already configured properly.
Breaking my head for a long time ! Thanks in advance for any kind of help here.

Related

Spring 4, MVC and JPA integration

I'm kinda rusty in spring.
I have a proyect using JPA persitence, and i need to make it so it return JSON on a rest API.
web.xml
<display-name>display name</display-name>
<!-- Spring -->
<context-param>
<description>Spring context file</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/META-INF/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
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-1.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config/>
<context:load-time-weaver/>
<!-- escanea las clases del package services buscando componentes -->
<context:component-scan base-package="cl"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- MYSQL -->
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect">
<!-- <property name="databasePlatform" value="org.eclipse.persistence.platform.database.H2Platform" /> -->
<!-- <property name="showSql" value="true" /> -->
</bean>
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="persistenceUnitName" value="persistenceUnit"></property>
<property name="jpaDialect" ref="jpaDialect"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"/>
</property>
<!--
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
</map>
</property>
-->
</bean>
<!-- Transaccion manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<!-- JPA Repositories -->
<jpa:repositories base-package="cl.repositories"></jpa:repositories>
<!-- traductor de excepciones de repo -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<!-- Velocity -->
</beans>
Service Class
#Service
public class CalculatorService {
private transient Logger logger = LoggerFactory.getLogger(CalculatorService.class);
#Autowired
RubroRepository rubroRepo;
...
I created a RestController following many guides in internet, but always got problems, like, the autowired to the class CalculatorService dosnt work.
Whats is the best way to include a rest servlet in this application?
Thanks
Well, i figured it out in the end, i was putting the applicationContext.xml outside of the resource folder, so i never had the services bean in place.
it took me a lot of time to figure this out, so i think i may be missing some important log output. I'm only watching tomcat output on this. so any help in this regard would be appreciated.

How can I run fast my project?

Here is my database.properties file which use for store database
information
################### JDBC Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eduman_em?
verifyServerCertificate=false&useSSL=false&requireSSL=false
jdbc.username=root
jdbc.password=1234
########## Hibernate Configuration #########
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#### hibernate.show_sql=true
#### hibernate.hbm2ddl.auto=update
#### hibernate.generate_statistics=true
hibernate.connection.charSet=UTF-8
hibernate.ejb.naming_
strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.cache.provider_class=
org.hibernate.cache.HashtableCacheProvider
################## For List insertion Hiber Config
###hibernate.order_inserts=true###
####hibernate.order_updates=true####
This is my **applicationContext-db.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!-- Scan for property files -->
<context:property-placeholder location="classpath:META-INF/spring/*.properties"/>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Detect #Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<!-- Define Hibernate JPA Vendor Adapter -->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- <property name="generateDdl" value="true" /> -->
<property name="database" value="MYSQL" />
</bean>
</property>
<!-- Persistence Unit -->
<property name="persistenceUnitName" value="persistenceUnit"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
I use mysql database. my database size 552 MB. when I run my project it takes more then 5 min.If I use 100 MB below/small database then it run fast. How can I run first my project.
Thanks.
# Nasir
You can go for Hikari Connection Pool.Return Hikari DataSource object.Sample code as below :
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
#Bean
public DataSource dataSource() {
// In classpath from spring-boot-starter-web
final Properties props = new Properties();
props.put("driverClassName", "com.mysql.jdbc.Driver");
props.put("jdbcUrl", "jdbc:mysql://localhost:3306/master?createDatabaseIfNotExist=false");
props.put("username", "root");
props.put("password", "mysql");
HikariConfig hc = new HikariConfig(props);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}

Spring 4 Jpa Hibernate - Can't Inject EntityManager

I guess I have the same problem as many people, but unsolved on most of cases. I will try anyway, hope you guys can help me.
The problem is in my repository when I try to inject que Entity Manager using #persistenceContext annotation and always comes null.
The stack:
Spring 4.2.5
Spring Data 1.10.1
Hibernate 5
This is my xml for Sprint data:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="conquerPU"/>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="packagesToScan" value="com.conquer.module" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/conquer" />
<property name="username" value="app" />
<property name="password" value="10203040" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<jpa:repositories base-package="com.conquer.module" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
This is my application context.xml
<context:annotation-config/>
<context:component-scan base-package="com">
<context:include-filter type="aspectj" expression="com.*" />
</context:component-scan>
<!-- a HTTP Session-scoped bean exposed as a proxy -->
<bean id="sessionData" class="com.conquer.common.SessionData" scope="session">
<aop:scoped-proxy/>
</bean>
<!--Hibernate persistence interceptor - Used for audit data-->
<bean id="hibernateInterceptor" class="com.conquer.module.security.interceptor.HibernateInterceptor"></bean>
<!--Application Context to be used anywhere-->
<bean id="applicationContextProvder" class="com.conquer.common.ApplicationContextProvider"/>
<!-- SpringMVC -->
<import resource="spring-mvc.xml"/>
<!-- SpringData -->
<import resource="spring-jpa.xml"/>
<!-- SpringSecurity -->
<import resource="spring-security.xml"/>
This is my repository
#Repository
#Transactional
public class BaseRepositoryImpl<T, ID extends Serializable> implements BaseRepository<T, ID> {
#PersistenceContext
public EntityManager em;
public RepositoryFactorySupport baseFactory;
public BaseRepository<T, ID> baseRepository;
public BaseRepositoryImpl() {
System.out.println("BASE REPOSITORY RUNNING...");
this.baseFactory = new JpaRepositoryFactory(em);
this.baseRepository = this.baseFactory.getRepository(BaseRepository.class);
}
// Implementations here ...
}
This is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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">
<persistence-unit name="conquerPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect"/>
<property name = "hibernate.show_sql" value = "true" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.interceptor" value="com.conquer.module.security.interceptor.HibernateInterceptor"/>
</properties>
</persistence-unit>
</persistence>
Although this question is quite old, we faced with this problem as well and solved it by adding this bean to our application context:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
The documentation for context:annotation-config clearly states that this should not be necessary, but in our case it was (albeit we use Spring 4.2 inside Eclipse Virgo 3.7 with Gemini Blueprint, so this setup is probably far from mainstream).

How do I set flush mode to "COMMIT" in my configuration files?

I'm using Spring 3.1.1.RELEASE, Hibernate 4.1.0.Final, and JPA 2.0. Is there a way I can configure Spring transactions to commit after the transactions are executed without Java code? In other words, I would like to set flush mode to commit in either the application context file, hibernate configuration file, or persistence.xml file. My Spring transaction service class looks like
#Transactional(rollbackFor = Exception.class)
#Service
public class ContractServiceImpl implements ContractService
{
#Autowired
private ContractDAO m_contractDao;
public void addContract(Contract contract)
{
m_contractDao.create(contract);
}
...
and my application context is set up like so …
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:myproject" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="persistenceXmlLocation" value="classpath*:META-INF/test-persistence.xml"/>
<property name="persistenceUnitName" value="testingDatabase"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="sharedEntityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven />
My persistence.xml file is
<persistence version="2.0"
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_2_0.xsd">
<persistence-unit name="testingDatabase" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.ejb.cfgfile" value="/hsql_hibernate.cfg.xml" />
<property name="org.hibernate.FlushMode" value="commit" />
</properties>
</persistence-unit>
</persistence>
and my hibernate config file is
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<mapping class="org.mainco.subco.sbadmin.domain.Product" />
<mapping class="org.mainco.subco.sbadmin.domain.Contract" />
<mapping class="org.mainco.subco.organization.domain.Country" />
<mapping class="org.mainco.subco.organization.domain.State" />
<mapping class="org.mainco.subco.organization.domain.Address" />
<mapping class="org.mainco.subco.organization.domain.OrganizationType" />
<mapping class="org.mainco.subco.organization.domain.Organization" />
</session-factory>
</hibernate-configuration>
Try the following in your web.xml
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>flushMode</param-name>
<param-value>COMMIT</param-value>
</init-param>
</filter>
Reference.
Check this link
You may need to extend
org.springframework.orm.jpa.vendor.HibernateJpaDialect
I hope this helps!
As another option, you can configure the Hibernate EntityManager directly to use a particular flush mode by default using the org.hibernate.flushMode configuration setting.
I am not sure if this type of setting is available in spring. (I haven't seen one) But,
as an alternative hibernate provides generic CRUD methods that you can use for all your classes if you pass them in as generics. Just put the call to the flush method in the Update/Create methods and use these exclusively to create/update all your classes.
Here is an example:
http://www.ibm.com/developerworks/java/library/j-genericdao/index.html

PersistenceAnnotationBeanPostProcessor vs JpaVendorAdapter

I'm setting up a maven-spring-hibernate-mysql-tomcat environment.
I would like to inject my Entity manager using the #PersistenceContext annotation.
As I understand to do this, I should have PersistenceAnnotationBeanPostProcessor defined in my application context, pointing to my persistence.xml file.
In this case my application context could be looking like this more or less:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task" xmlns:ox="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
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/jee http://www.springframework.org/schema/jee/spring-jee-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/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- Context -->
<context:component-scan base-package="com.yl.mypack" />
<!-- AOP -->
<aop:aspectj-autoproxy />
<!-- Properties -->
<context:property-placeholder
location="classpath:db.connection.properties,applicationProperties.properties" />
<!-- DB Connection Pool -->
<bean id="dataSourceGlobal" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- Data Source -->
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
<!-- C3P0 Connection pool properties -->
<property name="minPoolSize" value="${c3p0.min_pool_size}" />
<property name="maxPoolSize" value="${c3p0.max_pool_size}" />
<property name="unreturnedConnectionTimeout" value="${c3p0.timeout}" />
<property name="idleConnectionTestPeriod" value="${c3p0.idle_test_period}" />
<property name="maxStatements" value="${c3p0.max_statements}" />
<property name="automaticTestTable" value="${c3p0.automatic_test_table}" />
</bean>
<!-- JPA -->
<!-- Creates a EntityManagerFactory for use with the Hibernate JPA provider -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="myPU" />
<property name="dataSource" ref="dataSourceGlobal" />
</bean>
<!-- In order to enable EntityManager injection -->
<bean id="persistenceAnnotation"
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="persistenceUnits">
<map>
<entry key="myPU" value="classpath:META-INF/persistence.xml" />
</map>
</property>
</bean>
<!-- Transactions -->
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSourceGlobal" />
</bean>
</beans>
My persistence.xml could look like this:
<persistence-unit name="myPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.transaction.flush_before_completion"
value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
So now I guess I should be able to inject my entity manager using the #PersistenceContext annotation, at list this is what I get from the documentation. Before I'mm getting to JpaVendorAdapter, my first question would refer the entity manager factory definition:
The following properties:
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="myPU" />
Are these required to be referred from the entity manager factory? Is it a must?
My second question would be regarding the JpaVendorAdapter, and in my case HibernateJpaVendorAdapter.
If I use HibernateJpaVendorAdapter, do I still need to have a persistence.xml file? Since some of the properties are overlapping. Moreover, do I still need to have PersistenceAnnotationBeanPostProcessor defined, pointing to my persistence.xml file? Can these 2 go together (PersistenceAnnotationBeanPostProcessor and HibernateJpaVendorAdapter)? Should they go together? What is the best practice, assuming I'm avoiding any JDNI style definitions?
Thanks in advance
The combination of data source bean and HibernateJpaVendorAdapter allows you to get rid of persistence.xml with Spring 3.1. Check out this article:
http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/
So the answers:
They are not a must.
No, you don't need to have a persistence.xml.
I am not exactly sure of what use PersistenceAnnotationBeanPostProcessor is.
<context:component-scan base-package="com.demo.dao" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="hibernate-resourceLocal"/>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My Spring application context xml looks as simple as this. And it is working.
I don't what the best practice is, but I will keep persistence.xml so that in case I need to expose my service as session bean, it can be easily done.

Resources