Spring-dispatcher-servlet.xml to Java Config - java

Hi i'm trying to convert my Xml configuration to Java Config. I'm really lost now.
Here is the spring-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- package of spring controller -->
<context:component-scan base-package="com.test" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0" />
</bean>
<mvc:resources mapping="/Resources/**" location="/Resources/"
cache-period="31556926" />
<bean id="viewResolver1" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location" value="/WEB-INF/excel-view.xml" />
</bean>
<bean id="viewResolver2"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="100000" />
</bean>
<!-- Read test.properties -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:test.properties</value>
</property>
</bean>
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.beo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager. Exposes
Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
<!-- <prop key="hibernate.show_sql">true</prop> -->
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
<!-- Hikari Config -->
<property name="dataSourceClassName" value="${hikari.dataSourceClassName}" />
<property name="maximumPoolSize" value="${hikari.maximumPoolSize}" />
<property name="maxLifetime" value="${hikari.maxLifetime}" />
<property name="idleTimeout" value="${hikari.idleTimeout}" />
<property name="dataSourceProperties">
<props>
<prop key="url">${jdbc.url}</prop>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
</props>
</property>
</bean>
<!-- This transaction manager is appropriate for applications that use a
single JPA EntityManagerFactory for transactional data access. JTA (usually
through JtaTransactionManager) is necessary for accessing multiple transactional
resources within the same transaction. -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<!-- responsible for registering the necessary Spring components that power
annotation-driven transaction management; such as when #Transactional methods
are invoked -->
<tx:annotation-driven />
</beans>
Here is what i came up for the Java Config.
#Configuration
#EnableWebMvc
#ComponentScan("com.test")
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/Resources/**")
.addResourceLocations("/Resources/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public ViewResolver setupViewResolver(ContentNegotiationManager manager) {
List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
InternalResourceViewResolver InternalResourceResolver = new InternalResourceViewResolver();
InternalResourceResolver.setPrefix("/WEB-INF/jsp/");
InternalResourceResolver.setSuffix(".jsp");
resolvers.add(InternalResourceResolver);
ContentNegotiatingViewResolver resolver2 = new ContentNegotiatingViewResolver();
resolver2.setViewResolvers(resolvers);
resolver2.setContentNegotiationManager(manager);
return resolver2;
}
}
Thank you so much in advance for the help.

Related

Spring boot JPA set custom datasource

I have 2 datasources defined-
#datasource jndi setup
database.datasources[1].jndi-name=jdbc/yyyy
database.datasources[1].username=yyyy
database.datasources[1].password=yyyyy
database.datasources[1].url=jdbc:oracle:thin:#localhost:2222:webtst
database.datasources[1].driverClassName=oracle.jdbc.OracleDriver
database.datasources[1].factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.datasources[1].initialSize=1
database.datasources[1].maxActive=5
database.datasources[0].jndi-name=jdbc/xxx
database.datasources[0].username=xxx
database.datasources[0].password=xxxx
database.datasources[0].url=jdbc:oracle:thin:#localhost:2222:webtst
database.datasources[0].driverClassName=oracle.jdbc.OracleDriver
database.datasources[0].factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.datasources[0].initialSize=1
database.datasources[0].maxActive=15
And 2 matching JPA repositories, how can I set one of them to use different ds(not the primary one) after I defined one of them to be #Primary :
#Bean
#Primary
DataSource dataSource() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(xusername);
dataSource.setPassword(xpassword);
dataSource.setURL(xurl);
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Bean
DataSource propsDataSource() throws SQLException {
OracleDataSource propsDataSource = new OracleDataSource();
//propsDataSource.setDataSourceName(secJNDIName);
propsDataSource.setUser(yUserName);
propsDataSource.setPassword(ypropsPassword);
propsDataSource.setURL(upropsUrl);
propsDataSource.setImplicitCachingEnabled(true);
propsDataSource.setFastConnectionFailoverEnabled(true);
return propsDataSource;
}
And a simple JpaRepository that I want it to use seconday data-source:
public interface AttributesRepo extends JpaRepository<PRODUCTATTRIBUTE, PRODUCTATTRIBUTE_KEY> {
}
You need to:
define two DataSource
mark one of them as #Primary (like you did)
define two LocalContainerEntityManagerFactoryBean em1 and em2 each using a different DataSource
define two TransactionManagers
put all the repositories which should use the first DataSource into package pkg1 and the other repositories into package pkg2
define a #Configuration class with #EnableJpaRepositories with basePackages = "pkg1" and entityManagerFactoryRef = "em1"
add the second #Configuration class for pkg2 and em2
It is described in the Spring Boot documentation - 8.2 Configure Two DataSources.
I use two datasources. This is my applicationContext.xml:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
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:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="nl.christine.schwartze.server"/>
<context:property-placeholder location="classpath:/META-INF/database.properties"/>
<context:component-scan base-package="nl.christine.schwartze.server"/>
<bean class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
<bean class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close" id="importDataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${importDatabase.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="defaultPU"/>
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="nl.christine.schwartze.server.model"/>
<property name="jpaVendorAdapter" ref="hibernateVendorAdapter"/>
<property name="jpaProperties" ref="props"/>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
</bean>
<bean id="importEntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="importPU"/>
<property name="dataSource" ref="importDataSource"/>
<property name="packagesToScan" value="nl.christine.schwartze.server.modelimport"/>
<property name="jpaVendorAdapter" ref="hibernateVendorAdapter"/>
<property name="jpaProperties" ref="importprops"/>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="importTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="importEntityManagerFactory" />
</bean>
<bean id="hibernateVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<util:properties id="props">
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">${database.createorvalidate}</prop>
<prop key="hibernate.ddl-auto">${database.createorvalidate}</prop>
<prop key="spring.jpa.show-sql">true</prop>
<prop key="spring.jpa.generate.ddl">true</prop>
<prop key="spring.jpa.hibernate.ddl-auto">${database.createorvalidate}</prop>
<prop key="spring.datasource.initialization-mode">never</prop>
<prop key="spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation">true</prop>
</util:properties>
<util:properties id="importprops">
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.id.new_generator_mappings">false</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.ddl-auto">validate</prop>
<prop key="spring.jpa.show-sql">true</prop>
<prop key="spring.jpa.generate.ddl">true</prop>
<prop key="spring.jpa.hibernate.ddl-auto">validate</prop>
<prop key="spring.datasource.initialization-mode">never</prop>
<prop key="spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation">true</prop>
</util:properties>
<bean id="importLetterDao" class="nl.christine.schwartze.server.daoimport.impl.ImportLetterDaoImpl" scope="singleton">
</bean>
<bean id="letterDao" class="nl.christine.schwartze.server.dao.impl.LetterDaoImpl" scope="singleton">
</bean>
<bean id="locationDao" class="nl.christine.schwartze.server.dao.impl.LocationDaoImpl" scope="singleton">
</bean>
<bean id="personDao" class="nl.christine.schwartze.server.dao.impl.PersonDaoImpl" scope="singleton">
</bean>
<bean id="letterService" class="nl.christine.schwartze.server.service.impl.LetterServiceImpl" scope="singleton">
</bean>
<bean id="logger" scope="prototype" class="org.slf4j.LoggerFactory" factory-method="getLogger">
<constructor-arg name="name" value="schwartzeLogger" />
</bean>
This is part of one of the domain classes:
#Entity
#Table(name = "letters")
#EnableJpaRepositories(
basePackages = "nl.christine.schwartze.server.dao",
transactionManagerRef = "transactionManager",
entityManagerFactoryRef = "defaultPU")
public class Letter {
...
These are annotations I have on a Controller method:
#CrossOrigin(origins = "http://pengo.christine.nl:3000")
#RequestMapping(method = RequestMethod.POST, value = "/get_letters/")
#Transactional("transactionManager")
public ResponseEntity<LettersResult> getLetters(#RequestBody LettersRequest request) {
...
Example project here.

SessionFactory is null with Spring 4 and Hibernate 4

When I try to save data to DB the SessionFactory is null. Find the code below.
Spring configuration
<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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Specifying base package of the Components like Controller, Service, DAO -->
<context:component-scan base-package="com.service.jaxws" />
<!-- Getting Database properties -->
<!-- <context:property-placeholder location="classpath:application.properties" /> -->
<mvc:annotation-driven />
<!-- Specifying the Resource location to load JS, CSS, Images etc -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- View Resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- DataSource -->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/hrms"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.service.jaxws"></property>
</bean>
<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
Repository Bean
#Repository
public class UserDAOImpl implements UserDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(UserBO user) {
if (sessionFactory != null) {
sessionFactory.getCurrentSession().save(user);
} else {
System.out.println("Null");
}
}
}
When debugging each and every time the SessionFactory is null. Could anyone please tell me what I am missing?
Thanks in advance
Serin
Matt the issue has been resolved. The main problem was with the #Autowired. it was not working as expected. I tried this in my #Webservice class. After using the extends SpringBeanAutowiringSupport it is working properly. Anyway thanks for your support.

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>

org.springframework.beans.NotWritablePropertyException

I try to run a spring project using LocalSessionFactory, I get a null pointer 'cause I've to init the classLoader. Any way I got this exception at the end!
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactoryClassLoader' of bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Bean property 'sessionFactoryClassLoader' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?
any suggestions?
Here is the implementation:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.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">
<!-- Data Source Declaration -->
<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/Database" />
<property name="username" value="postgres" />
<property name="password" value="password" />
</bean>
<!-- Session Factory Declaration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource"></property>
<property name="mappingLocations">
<list>
<value>classpath:META-INF/products.xml
</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
<property name="sessionFactoryClassLoader" ref="portletClassLoader" />
</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.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="portletClassLoader" class="com.liferay.portal.kernel.portlet.PortletClassLoaderUtil" factory-method="getClassLoader" />
</beans>
by the way I want to replace com.liferay.portal.kernel.portlet.PortletClassLoaderUtil by another classLoader using springFramework or hibernate Libraries!
sessionFactoryClassLoader is not a property of org.springframework.orm.hibernate3.LocalSessionFactoryBean.
It is available for PortletSessionFactory implementation which extends SessionFactoryImpl.

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