I am having trouble figuring out how to configure EclipseLink with Spring without using a Persistence.xml file. I want to configure static weaving with EclipseLink too to avoid all those pesky LazyLoadExceptions from Hibernate.
The following was my Hibernate & Spring configuration that worked fine. I want to do something similar with EclipseLink but really struggling to find complete and relevant docs.
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
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-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:annotation-config />
<jpa:repositories base-package="com.something.ots.repository" />
<jee:jndi-lookup jndi-name="${datasource.jndi.name}" id="dataSource" expected-type="javax.sql.DataSource" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="packagesToScan">
<list>
<value>com.dscreative.honda.ots</value>
</list>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.connection.charSet">${hibernate.connection.charSet}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${jpa.vendor.database}" />
<property name="showSql" value="${jpa.vendor.showSql}"/>
<property name="generateDdl" value="${jpa.vendor.generateDdl}"/>
<property name="databasePlatform" value="${jpa.vendor.databasePlatform}"/>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
I am using spring data with EclipseLink with PostgreSql dbms.My configuration is annotation based. It is easy to transform it to xml configuration. The above is my persistent configuration,
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.commons.dbcp.BasicDataSource;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableJpaRepositories(basePackages = {
"package.with.repositories1",
"package.with.repositories2"
})
#EnableTransactionManagement
public class PersistenceContext {
#Bean(destroyMethod = "close")
DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/dbName");
dataSource.setUsername("usernameForDd");
dataSource.setPassword("passwordForDd");
return dataSource;
}
#Bean
EclipseLinkJpaVendorAdapter jpaVendorAdapter() {
EclipseLinkJpaVendorAdapter jpaVendorAdapter = new EclipseLinkJpaVendorAdapter();
jpaVendorAdapter.setDatabasePlatform("org.eclipse.persistence.platform.database.PostgreSQLPlatform");
jpaVendorAdapter.setGenerateDdl(Boolean.FALSE);
jpaVendorAdapter.setShowSql(EnvironmentVariables.getInstance().getBoolean("app.showSql", Boolean.FALSE));
return jpaVendorAdapter;
}
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter());
entityManagerFactoryBean.setJpaDialect(new EclipseLinkJpaDialect());
// Instead of persistence.xml
entityManagerFactoryBean.setPersistenceUnitName("yourPersistenceUnitName");
entityManagerFactoryBean.setPackagesToScan(
"package.with.entities1",
"package.with.entities2"
);
Properties jpaProperties = new Properties();
jpaProperties.put(PersistenceUnitProperties.WEAVING, "static");
jpaProperties.put(PersistenceUnitProperties.CACHE_SHARED_DEFAULT, "false");
entityManagerFactoryBean.setJpaProperties(jpaProperties);
entityManagerFactoryBean.afterPropertiesSet();
entityManagerFactoryBean.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver());
return entityManagerFactoryBean;
}
#Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
Related
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.
I have a project with Spring 4 and we have a lot of #Transactional classes and methods over there. Everything works perfectly, but I can not to provide transactions driven by Spring 3 until I add AspectJ libs and special XML configs in context file. So I would like to know if Spring 4 implements something like AspectJ natively or am I doing something wrong?
UPDATED
this is xml file for 3d Spring
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<aop:config proxy-target-class="true" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="saveService" class="com.promptlink.stbtp.dao.billing.SaveService" />
<bean id="billingDaoImpl" class="com.promptlink.stbtp.dao.billing.BillingDaoImpl" />
<bean id="dbParams" class="com.promptlink.stbtp.dao.util.SessionManager"
factory-method="getDbParams">
</bean>
<bean id="url" factory-bean="dbParams" factory-method="getBillingUri" />
<bean id="user" factory-bean="dbParams" factory-method="getUser" />
<bean id="pass" factory-bean="dbParams" factory-method="getPassword" />
<bean id="driver" factory-bean="dbParams" factory-method="getDriver" />
<bean id="dialect" factory-bean="dbParams" factory-method="getDialect" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" ref="driver" />
<property name="url" ref="url" />
<property name="username" ref="user" />
<property name="password" ref="pass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.promptlink.stbtp.dao.billing</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">#{dialect}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<beans profile="webapp">
<bean id="billingDatabaseProcessor"
class="com.promptlink.stbtp.dao.statistics.billingReport.BillingDatabaseProcessorImpl"></bean>
</beans>
</beans>
UPDATED
For Spring 4 I have something like this for Hibernate
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class HibernateConfiguration {
#Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager(sessionFactory());
}
#Bean
public SessionFactory sessionFactory() {
return SessionManager.getSessionFactory();
}
}
And standard AnnotationConfigApplicationContext initializer
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.
My SessionFactory isn't being injected to SessionFactory variable. My configuration is as follows:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:annotation-config/>
<!-- Scans the package for contents -->
<context:component-scan base-package="com.csu.library.mvc"/>
<!-- Maps static resources like images, css, javascript files -->
<mvc:resources location="/resources/" mapping="/resources/**"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "viewClass" value = "org.springframework.web.servlet.view.JstlView"/>
<property name = "prefix" value = "/WEB-INF/jsps/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/csu_library"/>
<property name="username" value="csulibrary"/>
<property name="password" value="csulibrary"/>
<!-- Pool Properties -->
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id = "hibernateProperties" class = "java.util.Properties">
<constructor-arg index="0">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
</props>
</constructor-arg>
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value = "com.csu.library.mvc"/>
<property name="dataSource" ref = "dataSource"/>
<property name="hibernateProperties" ref = "hibernateProperties"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "sessionFactory"/>
</bean>
</beans>
HibernateUtil.class
package com.csu.library.mvc.hibernate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#org.springframework.context.annotation.Configuration
#EnableTransactionManagement
public class HibernateUtil {
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager(getSessionFactory());
}
#Bean
public HibernateExceptionTranslator exceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
The program throws NullPointerException when getSessionFactory() method is called. Obviously, sessionFactory isn't being injected. The program starts up fine. What could be the problem?
inject like following, it'll work fine
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
Hope to help you:)
In some Spring versions, sub folders are not scanned.
Either move your class in the package com.csu.library.mvc or add the package com.csu.library.mvc.hibernate in the scanned packages and give it a try.
You'll want to use the org.springframework.beans.factory.annotation.Autowired annotation instead of javax.inject.Inject.
#Autowired
private SessionFactory sessionFactory;
Note that only looks for annotations on beans in the same
application context it is defined in. This means that, if you put in
a WebApplicationContext for a DispatcherServlet, it only checks for #Autowired beans in your
controllers, and not your services.
I have one service class to do the DB operations through the DAO classes , i inject the DAO object using spring. It is working fine.
After that i exposed the same method as a webservice method using JAX-WS annotation.
After that it is not working it saying my dao object not get injected , so i am getting nullpointerexception. the way i am doing is correct or not?
My service class is
package com.tecnotree.upc.services.impl;
import com.tecnotree.upc.services.*;
import com.tecnotree.upc.entities.*;
import com.tecnotree.upc.dao.UpcLineOfBusinessDao;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.WebParam;
import javax.jws.soap.SOAPBinding;
import org.springframework.transaction.annotation.Transactional;
#WebService
#SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,
parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)
public class UpcLineOfBusinessServiceImpl implements UpcLineOfBusinessService {
private UpcLineOfBusinessDao upcLineOfBusinessDao;
public void setUpcLineOfBusinessDao(
UpcLineOfBusinessDao upcLineOfBusinessDao) {
this.upcLineOfBusinessDao = upcLineOfBusinessDao;
}
#Override
#Transactional
#WebMethod
public UpcLineOfBusinessEntity createUpcLineOfBusinessEntity(
UpcLineOfBusinessEntity upcLineOfBusinessEntity) {
try{
if(upcLineOfBusinessDao!=null)
return upcLineOfBusinessDao.create(upcLineOfBusinessEntity);
else
return null;
}
catch(Exception ex)
{
ex.printStackTrace();
return null;
}
}
}
My spring xml file is
<?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:p="http://www.springframework.org/schema/p"
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">
<bean id="upcDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#192.168.4.33:1521:lt33" />
<property name="username" value="UPC_PROD" />
<property name="password" value="UPC_PROD" />
</bean>
<bean id="upcSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="upcDataSource" />
<property name="mappingResources">
<list>
<value>/com/tecnotree/upc/hbmfiles/UpcLineOfBusinessEntity.hbm.xml
</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="upcSessionFactory" />
</property>
</bean>
<tx:annotation-driven />
<bean id="upcLineOfBusinessDao" class="com.tecnotree.upc.dao.impl.UpcLineOfBusinessDaoImpl">
<property name="sessionFactory">
<ref bean="upcSessionFactory" />
</property>
</bean>
<bean id="upcLineOfBusinessService" class="com.tecnotree.upc.services.impl.UpcLineOfBusinessServiceImpl">
<property name="upcLineOfBusinessDao">
<ref bean="upcLineOfBusinessDao" />
</property>
</bean>
I solved this issue by extending the SpringBeanAutowiringSupport in my service class . Now it is working fine . Thank you for all comments