How can I run fast my project? - spring

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;
}

Related

build jar with maven, contain a list of spring service and add it to war

I am using Spring with Maven and Tomcat. I have a Spring MVC application which has a public front-end WAR,and a shared services JAR. My JAR contain list of service annotated by spring annotation #Service and i configure my Application context inside this jar like bellow.
<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:sws="http://www.springframework.org/schema/web-services"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.bergit.jpa" />
<!-- Import file which containt parameter need it to configure the DB and hibernate -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="META-INF/config/jdbc.properties" />
<!-- Database connection settings -->
<bean id="dataSource-seconde"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<!-- Configuration for Hibernate/JPA -->
<bean id="entityManagerFactory-seconde"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="dataSource" ref="dataSource-seconde" /> -->
<property name="persistenceUnitManager" ref="pum"/>
<property name="persistenceUnitName" value="testspring-jpa-seconde" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="${jdbc.dialect}" />
</bean>
</property>
</bean>
<bean id="pum"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>META-INF/persistence.xml</value>
</list>
</property>
</bean>
<bean id="transactionManager-seconde"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory-seconde" />
<property name="dataSource" ref="dataSource-seconde" />
</bean>
</beans>
and this is my class java is writed like bellow:
#Service("userJARService")
public class UserJARServiceImpl implements UserJARService {...}
i tested my Jar using Junit and it's ok.
now i add this jar into my war (add inside the pom file of war).
i write my class of controller for my first view where i inject my first service which i want to use it inside this conctroller UserJARService like bellow:
#Controller
#RequestMapping(AccessClassToWebService.CONTROLLER_BASE_PATH)
public class AccessClassToWebService {
#Autowired
UserJARService userJARService;
}
now i add this jar dependency inside the pom of my war. But i get the error bellow
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.bergit.jpa.service.UserJARService ....

test and applicationContext

i use latest release of spring, spring data, jpa, hibernate and h2.
i try to run test (only repository test).
but i get this error: Failed to load ApplicationContext
my test class
#RunWith(SpringJUnit4ClassRunner.class)
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#Transactional
#ContextConfiguration(
locations = {"classpath:applicationContext-test.xml"})
public class UserDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
...
}
my applicationContext-test.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:property-placeholder location="classpath:/jdbc.properties"/>
<context:component-scan base-package="com.test.*" />
<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>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<jpa:repositories base-package="com.test.va.repository"/>
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="idleConnectionTestPeriodInMinutes" value="${jdbc.idleConnectionTestPeriodInMinutes}"/>
<property name="idleMaxAgeInSeconds" value="${jdbc.idleMaxAgeInSeconds}"/>
<property name="maxConnectionsPerPartition" value="${jdbc.maxConnectionsPerPartition}"/>
<property name="minConnectionsPerPartition" value="${jdbc.minConnectionsPerPartition}"/>
<property name="partitionCount" value="${jdbc.partitionCount}"/>
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
<property name="statementsCacheSize" value="${jdbc.statementsCacheSize}"/>
<property name="releaseHelperThreads" value="${jdbc.releaseHelperThreads}"/>
</bean>
so it's a config error.

Inject common attribute from spring configuration file to every test class

I have small clarification regarding the spring injection. I'm writing the test for services. Every Test class has a common attribute called "tenantId". Can I inject that attribute through spring configuration file.I don't want to add every test class to the spring configuration file, Is there a way to that?
#ContextConfiguration(locations = {"classpath*:applicationContext-service-test.xml"})
public class ApplicationServiceTest extends AbstractTestNGSpringContextTests {
#Autowired
TenantBasedSessionFactory tenantBasedSessionFactory;
#Autowired
private ApplicationService applicationService;
private String tenantId = "tenantId"; // I want this to inject from applicationContext-service-test.xml
private Session session;
}
Spring configuration file.
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Use #Transaction annotations for managing transactions -->
<tx:annotation-driven/>
<!-- Activates scanning of #Autowired -->
<context:annotation-config/>
<!-- Activates scanning of #Service and #Repository -->
<context:component-scan base-package="lk.gov.elg"/>
<!-- JDBC property file -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<!--<value>classpath:test.jdbc.properties</value>-->
<value>jdbc.properties</value>
</list>
</property>
</bean>
<!--<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"-->
<!--p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:test"-->
<!--p:username="sa" p:password="" />-->
<!-- create database connection pool -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!--<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">-->
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="100"/>
<property name="maxWait" value="1000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="defaultAutoCommit" value="true"/>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="lk.gov.elg.orm.model"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect.test}
hibernate.hbm2ddl.auto=update
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="tenantBasedSessionFactory" class="lk.gov.elg.orm.dao.impl.TenantBasedSessionFactoryImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
Thank you in advance
Cheers
You can create a common superclass for all your tests to inject there your tenantId. With this, you will only have to inject only once and tenandId will be available to all your desired classes.

Spring VelocityViewResolver not resolving

I get the following error when trying to set up a Spring project with Velocity.
PageNotFound - No mapping found for HTTP request with URI [/SpringMVCVelocity/Enquiries/viewAllEnquiries] in DispatcherServlet with name 'mvc-dispatcher'
I have set up the spring context.xml as-
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd">
<context:component-scan base-package="ecommerce.dao" />
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/view/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="false"/>
<property name="prefix" value=""/>
<property name="suffix" value=".vm"/>
<property name="order" value="-1"/>
<property name="exposeSpringMacroHelpers" value="true"></property>
</bean>
<mvc:annotation-driven/>
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="welcome"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ecommerce"/>
</bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
<!--
FLOW HANDLING
-->
<!-- Enables FlowHandler URL mapping -->
<bean id="flowController" class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" />
</bean>
<webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry"/>
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry" />
<property name="order" value="-1" />
</bean>
<webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices">
<webflow:flow-location path="/WEB-INF/view/flows/flow.xml"/>
</webflow:flow-registry>
<webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator" />
<bean id="mvcViewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers" ref="viewResolver" />
</bean>
<!--
Bean Injections
-->
<bean id="carModelDao" class="ecommerce.dao.CarModelDao"/>
<bean id="carController" class="ecommerce.controller.CarController">
<property name="carModelDao" ref="carModelDao"/>
</bean>
<bean id="veloController" class="ecommerce.controller.VelocityController">
<property name="carModelDao" ref="carModelDao"/>
</bean>
</beans>
My controller is:
#Controller
#RequestMapping("/Enquiries")
#SessionAttributes({"enqList", "search"})
public class EnquiryController {
private static final Logger logger = Logger.getLogger(EnquiryController.class);
private PagedListHolder<Enquiry> enqList = null;
private int pageSize = 10;
#Autowired
private EnquiryDao enquiryDao;
#RequestMapping("/viewAllEnquiries")
public String getAllEnquiries(#RequestParam(required=false) String page, Model model) {
if ("next".equals(page) && enqList != null) {
enqList.nextPage();
} else if ("previous".equals(page) && enqList != null) {
enqList.previousPage();
} else {
// well there is no page parameter, so it must be a new request
enqList = new PagedListHolder<Enquiry>(enquiryDao.getAllEnquiries());
enqList.setPageSize(pageSize);
}
model.addAttribute("search", new Search());
model.addAttribute("enqList", enqList);
return "viewAllEnquiries";
}
This controller is not even called. It does however successfully manage to resolve the welcome view with:
<mvc:view-controller path="/" view-name="welcome"/>
Problem solved,
I wasn't scanning the controller (context:component-scan) and had not wired the bean either in the Spring context.
So to fix it, I added it via spring injection:
<bean id="enquiryDao" class="ecommerce.dao.EnquiryDao"/>
<bean id="enquiryController" class="ecommerce.controller.EnquiryController">
<property name="enquiryDao" ref="enquiryDao"/>
</bean>

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