NullPointerException when accessing EntityManager - java

I am using Hibernate4,Spring3 and JSF2 for a small application and Weblogic 10.3.6 as Apps server.
In order to enable JPA2 I have added the following in commEnv.cmd
#rem Enable JPA 2.0 functionality on WebLogic Server
set PRE_CLASSPATH=%BEA_HOME%\modules\javax.persistence_1.1.0.0_2-0.jar;
%BEA_HOME%\modules\com.oracle.jpa2support_1.0.0.0_2-1.jar
When I run my application I am getting null pointer exception at the following line. How can I resolve this?
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
My DAO
#Named
public class RequestDAOImpl implements RequestDAO {
protected EntityManager entityManager;
public void getRequest(RequestQueryData data){
Map<String, String> filters = data.getFilters();
int start = data.getStart();
int end = data.getEnd();
String sortField = data.getSortField();
QuerySortOrder order = data.getOrder();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Request> c = cb.createQuery(Request.class);
Root<Request> emp = c.from(Request.class);
c.select(emp);
...... other code
applicationContext.xml
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="org.primefaces.spring.scope.ViewScope" />
</entry>
</map>
</property>
</bean>
<context:component-scan base-package="net.test" />
<!-- Data Source Declaration -->
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="oracle.jdbc" />
<property name="jdbcUrl"
value="jdbc:oracle:thin:#server:1521:ORCL" />
<property name="user" value="scott" />
<property name="password" value="tiger" />
<property name="maxPoolSize" value="10" />
<property name="maxStatements" value="0" />
<property name="minPoolSize" value="5" />
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>net.test.model.Request</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- Transaction Manager is defined -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
Update 1
applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Spring view scope customized -->
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="org.primefaces.spring.scope.ViewScope" />
</entry>
</map>
</property>
</bean>
<context:component-scan base-package="net.test" />
<!-- Data Source Declaration -->
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="oracle.jdbc" />
<property name="jdbcUrl"
value="jdbc:oracle:thin:#server:1521:ORCL" />
<property name="user" value="scott" />
<property name="password" value="tiger" />
<property name="maxPoolSize" value="10" />
<property name="maxStatements" value="0" />
<property name="minPoolSize" value="5" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<!-- JPA Entity Manager Factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="packagesToScan" value="net.test.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
</property>
</bean>
<bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" />
<!-- Session Factory Declaration -->
<bean id="SessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>net.test.model.Request</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations
<tx:annotation-driven transaction-manager="txManager" />-->
<!-- Transaction Manager is defined
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>-->
<!-- Transaction Config -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<tx:annotation-driven transaction-manager="txManager"/>
<context:annotation-config/>
<bean id="hibernateStatisticsMBean" class="org.hibernate.jmx.StatisticsService">
<property name="statisticsEnabled" value="true" />
<property name="sessionFactory" value="#{entityManagerFactory.sessionFactory}" />
</bean>
<bean name="ehCacheManagerMBean"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean">
<property name="locateExistingServerIfPossible" value="true" />
</bean>
<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="server" ref="mbeanServer" />
<property name="registrationBehaviorName" value="REGISTRATION_REPLACE_EXISTING"/>
<property name="beans">
<map>
<entry key="SpringBeans:name=hibernateStatisticsMBean" value-ref="hibernateStatisticsMBean" />
<entry key="SpringBeans:name=ehCacheManagerMBean" value-ref="ehCacheManagerMBean" />
</map>
</property>
</bean>
</beans>

Your EntityManager doesn't appear to be wired into your DAO. Add #Autowired, #PersistenceContext or a ref in your XML. Note that to just use #Autowired, you'll have to specify EntityManager as a bean.
Another possibility: if your DAO isn't also specified as a bean (either in the XML or using one of the various #Component annotatons (probably #Repository), Spring won't know to wire things in, either.
Update:
There's a couple different solutions here. Before those, though, make sure that you have
<mvc:annotation-driven />
In one of your XMLs. This will enable the spring annotations and save you a lot of headache from editing XMLs. Note that you'll also need to update the xmlns and schemaLocation in the <beans> tag.
xmlns:mvc="http://www.springframework.org/schema/mvc"
and
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
in the schemaLocation.
It looks like you're now specifying an EntityManagerFactory. That's a good start. You can now specify an EntityManager, too.
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
I can't vouch for your XML and EntityManagerFactory settings, though. You seem to have an </property> floating out there in the middle of nowhere.
I'm not sure how you're accessing your DAO. If it's already a bean and within the component-scan, you're good. If not, make sure to annotate your DAO class with #Repository and make sure its package is within the component-scan. Of course, if you don't already have it specified as a bean, that implies that you're possibly instantiating it elsewhere -- this is absolutely not how you want to be using your DAO. Should this be the case, I strongly recommend reading up on Spring's dependency injection.
Now you need to wire in your EntityManager. This can be done in two ways.
The first way requires that you specified it as a bean in your XML. If you've done that, just annotate your EntityManager field.
#Autowired
protected EntityManager entityManager;
Alternatively, since you're specifying a DataSource in your XML, you SHOULD be able to reference it by using #PersistenceContext and passing it a value of the ID.
#PersistenceContext(name="DataSource")
protected EntityManager entityManager;
I've never really used the latter method, but I've seen it done that way. I normally specify an EntityManager bean in the XML and use #Autowired, as described in the former method.

Related

What changes are required to use Hibernate along with IBatis and jdbc connection pooling

We want to integrate Hibernate 5 in our project, and complexity is that we are using IBatis with Spring 4
my persistence.xml looks like:
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/MYJNDI" />
<!-- SqlMap setup for iBATIS Database Layer -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:/sql-map-mysql.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven proxy-target-class="true" />
<!-- Generic Dao - can be used when doing standard CRUD -->
<bean id="baseDaoiBATIS" class="com.test.database.BaseDaoiBATIS">
<property name="dataSource" ref="dataSource" />
<property name="sqlMapClient" ref="sqlMapClient" />
</bean>
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:mybatis-resources/*.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.test.database.mapper" />
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.hostname}"></property>
<property name="port" value="${redis.port}"></property>
<property name="usePool" value="true"></property>
</bean>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer" ref="stringRedisSerializer"></property>
<property name="hashKeySerializer" ref="stringRedisSerializer"></property>
</bean>
</beans>
What changes we should do to have Hibernate5 along with IBatis Any suggestions would be greatly appreciated
Note: We are using spring4,Ibatis ,Connection pooling
We made changes as per suggestion by #M.Deinum and it's working:
Approach we followed are:
[1] using Hibernate-3 with spring 3
[2] using Hibernate Transaction Manager instead of DataSourceTransactionManager :
<!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> -->
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.test.database.domain" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

How to configure spring to use two different datasources. Getting a NoUniqueBeanDefinitionException for PlatformTransactionManger error

I'm working on spring boot application, which already has a database connection established in its applicationContext.xml file and the necessary transaction manager and vendors etc.
I now need to connect the app to a second database. But I'm having issues with this. In my unit tests the connection is fine and can make simple queries to retrieve data, which is all I need it to do. However when I compile the app into a jar and run it, I get the following error
NoUniqueBeanDefinitionException: No qualifying bean of type "org.springframework.transaction.PlatformTransactionManager" available: expected single matching bean but found 2: transactionManager, transactionManager2
I have spent ages looking up how to solve this, and the suggested fixes I have found here , here and here have not worked.
I have one persistence.xml with two persistence units defined. And in my applicaitonContext.xml I defined two datasources, two transaction managers and two entity Manager Factories. I then use the #persitsencecontext and #Transactional("") annotations to say which persistence unit and managers to use, but I still get an error. I also added in the <qualifier> tag to the app context file, as I saw this as a suggested fix with the #transactional annotation, still no luck.
My code is below, can anyone spot an errors I have made, and why it may not be working as expected
applicationContext.xml
<bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="..."/>
<property name="username" value="..."/>
<property name="password" value="..."/>
</bean>
<bean id="entityManagerFactory" name="proxy">
<property name="persistenceUnitName" value="proxy" />
<property name="persistenceUnitXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="dataSource" ref="dataSource1" />
<property name="jpaVendorAdapter" ref="hiberanteVendorAdapter" />
<property name="jpaProperties">
<props>
<prop key="hiberante.hbm2ddl.auto">valudate</prop>
</props>
</property>
</bean>
<bean id="hibernateVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
<property name="database" value="HSQL" />
<property name="showSql" value="true" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<qualifier value="transactionManager1" />
</bean>
<!-- Second datasource -->
<bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="..."/>
<property name="username" value="..."/>
<property name="password" value="..."/>
</bean>
<bean id="entityManagerFactory2" name="proxy">
<property name="persistenceUnitName" value="proxy2" />
<property name="persistenceUnitXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="dataSource" ref="dataSource2" />
<property name="jpaVendorAdapter" ref="hiberanteVendorAdapter2" />
<property name="jpaProperties">
<props>
<prop key="hiberante.hbm2ddl.auto">valudate</prop>
</props>
</property>
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory2" />
<qualifier value="transactionManager2" />
</bean>
<bean id="hibernateVendorAdapter2" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<tx:annotation-driven/>
Implementation
#Repository
#Transactional("transactionManager2")
public class myDaoImpl extends GenericJPADao<Integer, Integer> implements ImyDao {
#PersistenceContext(unitName="proxy2")
protected EntityManager em;
}
SOLUTION
The accepted answer was the correct solution for me, but a few things to note. The beans have to point to their respective entityManagerFactory's and you need to be careful on which bean you set the autowire-candidate="false" on, as I set it on the incorrect one at first, and had transactions rolled back as a result. I think there could be cleaner solution to this, but as a quick fix it works fine
try this :
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" autowire-candidate="false">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

How to use Persistence EntityManager along with SessionFactory in spring 4 hibernate 5?

I was using sessionFactory by autowiring it in my DAOImpl files.
Things were working fine until I started facing an issue of "Too many database connections" in certain DAO methods. After searching for possible reasons and solutions, I realized that I might have misconfigured my applicationContext.xml and the way I am using EntityManager is incorrect.
Below is my applicationContext.xml file content:
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- Enables the Spring MVC #Controller programming model -->
<!-- enables cors (cross origin request) for all urls -->
<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>
<!-- <mvc:annotation-driven /> -->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- Use the HibernateAware mapper instead of the default -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.typjaipur.core.objectmapper.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="com.typjaipur" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyPlaceholder" class="com.typjaipur.core.config.EnvironmentPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:core.properties</value>
<value>classpath:mailer.properties</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.typjaipur.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.default_batch_fetch_size">4</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<mvc:interceptors>
<bean class="org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<mvc:interceptor>
<mvc:mapping path="/**" />
<!-- excluded urls -->
<mvc:exclude-mapping path="/" />
<bean class="com.typjaipur.interceptor.ApiAuthenticationInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<!-- Enables swgger ui -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**"
location="classpath:/META-INF/resources/webjars/" />
<!-- Include a swagger configuration -->
<bean name="/applicationSwaggerConfig" class="com.typjaipur.config.SwaggerConfig" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<!-- <property name="maxUploadSize" value="100000"/> -->
</bean>
</beans>
Below is DAOImpl code example of how I am using EntityManager which is working too but I feel its not correct maybe.
#Repository
public class BusinessDetailsDAOImpl extends BaseDAOImpl<BusinessDetails, Long> implements BusinessDetailsDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<BusinessDetails> searchBusiness(BusinessSearchDTO businessSearchDTO, List<Long> businessIds) {
EntityManager entityManager = sessionFactory.getCurrentSession().getEntityManagerFactory().createEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<BusinessDetails> query = criteriaBuilder.createQuery(BusinessDetails.class);
Root<BusinessDetails> businessDetails = query.from(BusinessDetails.class);
List<Predicate> predicates = new ArrayList<Predicate>();
...//rest of code
It is tough for me to avoid sessionFactory at this point as I have used it all over my project. Is there anyway through which I can configure my xml file to allow me to use EntityManager as well as SessionFactory together?
I saw several examples of configuring EntityManager but none of them has added any line in xml file related to SessionFactory. So I am confused in this.
Use LocalContainerEntityManagerFactoryBean to create the EntityManager instead of using LocalSessionFactoryBean, so you do not have call sessionFactory.getCurrentSession().getEntityManagerFactory().createEntityManager() to get the entityManager :
In spring config file replace this current config with :
<!-- Create a datasource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<!-- Create an Hibernate to Jpa adapter -->
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="false" />
<property name="database" value="MYSQL" />
</bean>
<!-- persistenceUnitManager is optional -->
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="dataSource"/>
</bean>
<!-- create entityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaProperties">
<props>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<!-- and create transactionManager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
Use it like this :
#Repository
public class BusinessDetailsDAOImpl extends BaseDAOImpl<BusinessDetails, Long> implements BusinessDetailsDAO {
#PersistenceContext
protected EntityManager entityManager;
#Override
public List<BusinessDetails> searchBusiness(BusinessSearchDTO businessSearchDTO, List<Long> businessIds) {
// use directly entityManager instead of sessionFactory.getCurrentSession().getEntityManagerFactory().createEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// ...
}
Edit : update your config as follow :
<property name="jpaProperties">
<props>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- add this line -->
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>

Spring Hibernate Database Connections

I am in the process of learning Hibernate, Spring and JPA.
I would like to know whether my database connections are closed automatically by Spring or not. When I looked at database table v$session I can find there are four JDBC Thin Client
sessions. So would like to know whether these connections are from my application.
Below is my applicationContext.xml. Any help is highly appreciable.
<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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>
<context:component-scan base-package="net.test" />
<!-- Data Source Declaration -->
<bean id="DataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/myDS"/>
</bean>
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator" />
<!-- JPA Entity Manager Factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="packagesToScan" value="net.test.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="${jdbc.dialectClass}" />
</bean>
</property>
</bean>
<bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" />
<!-- Session Factory Declaration -->
<bean id="SessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>net.test.entity.Employee</value>
<value>net.test.entity.Department</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- <tx:annotation-driven transaction-manager="txManager"/> -->
<context:annotation-config />
<bean id="hibernateStatisticsMBean" class="org.hibernate.jmx.StatisticsService">
<property name="statisticsEnabled" value="true" />
<property name="sessionFactory" value="#{entityManagerFactory.sessionFactory}" />
</bean>
<bean name="ehCacheManagerMBean"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean">
<property name="locateExistingServerIfPossible" value="true" />
</bean>
<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter"
lazy-init="false">
<property name="server" ref="mbeanServer" />
<property name="registrationBehaviorName" value="REGISTRATION_REPLACE_EXISTING" />
<property name="beans">
<map>
<entry key="SpringBeans:name=hibernateStatisticsMBean"
value-ref="hibernateStatisticsMBean" />
<entry key="SpringBeans:name=ehCacheManagerMBean" value-ref="ehCacheManagerMBean" />
</map>
</property>
</bean>
</beans>
Spring closes connections when the transaction is committed of rollbacked. But the connections are pooled connections, so closing them simply puts them back into the pool of connections, and doen't physically closes them.
The first goal is to be able to get a new connection from the pool extremely quickly, without having to recreate a new physical connection each time, because it's a costly operation.
The other goal is to be able to put a limit on the number of opened connections, to avoid bringing the database to its knees.
Note that the pool of connections, in your case, isn't handled by Spring, but by your application server, which makes it available from JNDI.

Why am I getting an error while working with two datasources in Spring MVC?

I'm using Spring MVC with Hibernate. I'm trying to use two different databases (on two different servers). One is MySQL and the other is DB2.
Here is my dispatcher-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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Load JDBC Properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- Enable Annotations (MVC and Hibernate Transactions) -->
<context:component-scan base-package="com.example" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<!-- Tell Spring where to find static files and not use a controller -->
<mvc:resources mapping="/css/**" location="/WEB-INF/css/*" />
<mvc:resources mapping="/js/**" location="/WEB-INF/js/*" />
<!-- Create a ViewResolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Create a DataSource for MySQL -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.database.driver}" />
<property name="url" value="${mysql.database.url}" />
<property name="username" value="${mysql.database.user}" />
<property name="password" value="${mysql.database.password}" />
</bean>
<!-- Create a DataSource for DB2 -->
<bean id="db2DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db2.database.driver}" />
<property name="url" value="${db2.database.url}" />
<property name="username" value="${db2.database.user}" />
<property name="password" value="${db2.database.password}" />
</bean>
<!-- Create a Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.example.model.entities.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${mysql.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${mysql.hibernate.show_sql}</prop>
<prop key="hibernate.c3p0.min_size">${mysql.hibernate.c3p0.min_size}</prop>
<prop key="hibernate.c3p0.max_size">${mysql.hibernate.c3p0.max_size}</prop>
<prop key="hibernate.c3p0.timeout">${mysql.hibernate.c3p0.timeout}</prop>
<prop key="hibernate.c3p0.max_statements">${mysql.hibernate.c3p0.max_statements}</prop>
<prop key="hibernate.c3p0.idle_test_period">${mysql.hibernate.c3p0.idle_test_period}</prop>
</props>
</property>
</bean>
<bean id="sessionFactoryDB2" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="db2DataSource" ref="db2DataSource" />
<property name="annotatedClasses">
<list>
<value>com.example.model.entities.Transfer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db2.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${db2.hibernate.show_sql}</prop>
<prop key="hibernate.c3p0.min_size">${db2.hibernate.c3p0.min_size}</prop>
<prop key="hibernate.c3p0.max_size">${db2.hibernate.c3p0.max_size}</prop>
<prop key="hibernate.c3p0.timeout">${db2.hibernate.c3p0.timeout}</prop>
<prop key="hibernate.c3p0.max_statements">${db2.hibernate.c3p0.max_statements}</prop>
<prop key="hibernate.c3p0.idle_test_period">${db2.hibernate.c3p0.idle_test_period}</prop>
</props>
</property>
</bean>
<!-- Create a Transaction Manager -->
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="sessionFactoryDB2" ref="sessionFactoryDB2" />
</bean>
</beans>
But when I run I get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transfersController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.example.model.service.UserService....
I am using #Autowired in my controllers/models. So it makes sense that it doesn't know which bean to use to autowire. But how do I solve this?
Thanks
<bean id="sessionFactoryDB2" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="db2DataSource" ref="db2DataSource" />
<property name="annotatedClasses">
I don't think there is a property named db2DataSource in AnnotationSessionFactoryBean. That may be one of the reason it is failing. It should be <property name="dataSource" ref="db2DataSource" /> instead.
I think problem does not exist with your dataSources. To autowire service classes you need to use #Service(preferred for service layer classes) stereotype annotation.
You also need to scan these annotated classes using component scan which I didn't see in your posted xml.
<context:component-scan base-package="com.example, com.example.model.service" />

Categories

Resources