I'm currently working on some implementation with Hibernate4, Spring and JPA, but I'm having some troubles regarding the creation of my Bean.
In the application, we are using one SQL Server database with their respective configurations (C3p0 class, dataSource, *hibernate.cfg.xml and applicationContext) and It works.
But when I tried to configure another database (PostgreSQL) and test it with JUnit, it seems that is not able to create the new connection to the PostgreSQL database.
But I verified the access and they work in a external dbview program. Please consider the following:
Stacktrace:
Caused by:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'transactionManager' defined in class path resource [config/applicationContext.xml]:
Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory';
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in class path resource [config/hibernate.cfg.xml]: Invocation of init method failed;
nested exception is java.lang.NullPointerException
My hibernate.cfg.xml:
<bean id="dataSourceFactory" class="com.package.myapplication.c3p0">
<constructor-arg type="String" value="${driverClassName}"/>
<constructor-arg type="String" value="${url}" />
<constructor-arg type="String" value="${user}" />
<constructor-arg type="String" value="${password}" />
</bean>
<bean id="dataSource" factory-bean="dataSourceFactory" factory-method="createDriverManagerDataSource"></bean>
<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.PostgreSQLDialect
</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.max_size">100</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.package.myapplication.EntityClass</value>
</list>
</property>
</bean>
applicationContext.xml:
<beans>
<context:property-placeholder location="classpath:/database/db.properties" />
<context:annotation-config />
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<import resource="classpath:/config/hibernate.cfg.xml" />
</beans>
and finally I'm using the following headers to load the applicationContext.xml:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="classpath:/config/applicationContext.xml")
#Transactional
public class UnitTest(){
....
}
Is it possible that the application cannot handle multiple connections (datasources)? Or Is there another way to make it works?
Change your hibernate.cfg.xml as below:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.package.myapplication" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.max_size">100</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
</props>
</property>
And make sure you are Hibernate 4 depenencies:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
Related
New to Hibernate and Spring. So I copied and pasted some configurations online and did the rest myself.
However when I try to start my Jetty server I am getting a Spring error.
Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/data/jpa]
What does this mean?
<?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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<jpa:repositories base-package="com.testproject.testpackage.example1.repository"
transaction-manager-ref="example1TransactionManager"
entity-manager-factory-ref="example1EntityManagerFactory">
<repository:include-filter type="regex" expression=".*Repository"/>
</jpa:repositories>
<bean id="example1hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="example1Datasource"/>
<property name="connectiontestprojectQuery" value="SELECT 1"/>
<property name="dataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"/>
<property name="minimumIdle" value="5"/>
<property name="maximumPoolSize" value="40"/>
<property name="idleTimeout" value="2000"/>
<property name="dataSourceProperties">
<props>
<prop key="url">${db.url}</prop>
<prop key="user">${db.username}</prop>
<prop key="password">${db.password}</prop>
</props>
</property>
</bean>
<bean id="example1Datasource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="example1hikariConfig"/>
</bean>
<bean id="hibernate.properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.show_sql">${hibernate.showSql}</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
</props>
</property>
</bean>
<bean id="example1EntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="example1"/>
<property name="dataSource" ref="example1Datasource"/>
<property name="persistenceProviderClass" value="org.hibernate.jpa.HibernatePersistenceProvider"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan">
<list>
<value>com.testproject.testpackage.example1.repository</value>
</list>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="jpaPropertyMap" ref="hibernate.properties"/>
</bean>
<bean id="example1TransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="example1EntityManagerFactory"/>
<qualifier value="example1"/>
</bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven/>
</beans>
Replace the url in the beans tag
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
with
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
It seems that the spring-data-jpa-{version}.jar is not included in you project.
Check the library or dependency.
I have test which is green when it is launched directly through IDE.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:dao/daoTest-context.xml"})
#ActiveProfiles(profiles = "test")
public class ClientDaoTest {
#Autowired
ClientDao clientDao;
#Test
public void shouldSaveClientInDBTest(){
Client client = new Client();
client.setName("ivan");
client = clientDao.saveClient(client);
assertNotNull(client.getId());
assertEquals("ivan", client.getName());
}
}
daoTest-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-context.xml" />
<beans profile="test">
<bean id="ConnectionDB" name="ConnectionDB" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="biz.podoliako.carwash.services.impl.ConnectDB" />
</bean>
<bean id="myDataSourceTest" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:~/test"/>
<property name="username" value=""/>
<property name="password" value=""/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSourceTest"/>
<property name="packagesToScan" >
<list>
<value>biz.podoliako.carwash</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.connection.pool_size">1</prop>
</props>
</property>
</bean>
</beans>
However when maven command "mvn test" run this test it throws:
Tests in error: shouldSaveClientInDBTest(dao.ClientDaoTest): Failed to load ApplicationContext
and the main explanation is:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ConnectionDB' defined in class path resource [dao/daoTest-context.xml]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.lang.Object]: Factory method 'mock' threw exception**; nested exception is org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Example of correct verification:
verify(mock).doSomething()
Also, this error might show up because you verify either of:
final/private/equals()/hashCode() methods.
Those methods cannot be stubbed/verified.
Please help me to find out what I did wrong.
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.
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" />
hi i am getting the following exception while running my application
and my applicationContext.xml 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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost/SureshDB"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/jsfcompref/register/UserTa.hbm.xml</value></list>
</property></bean>
<bean id="UserTaDAO" class="com.jsfcompref.register.UserTaDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="UserTaService" class="com.jsfcompref.register.UserTaServiceImpl">
<property name="userTaDao">
<ref bean="UserTaDAO"/>
</property>
</bean>
</beans>
Error creating bean with name
'sessionFactory' defined in class path
resource [applicationContext.xml]:
Invocation of init method failed;
nested exception is
java.lang.NoSuchMethodError:
org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
any suggestion would be heplful
Your exception
nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit
Hibernate depends on asm
Go to Spring installation directory and include all of jars in the following folders
<SPRING_HOME>/lib/asm/
<SPRING_HOME>/lib/dom4j/
<SPRING_HOME>/lib/antlr/
<SPRING_HOME>/lib/jakarta-commons/
<SPRING_HOME>/lib/javassist
<SPRING_HOME>/lib/cglib/
<SPRING_HOME>/lib/hibernate // without hibernate-entitymanager.jar
<SPRING_HOME>/lib/slf4j/
<SPRING_HOME>/lib/j2ee/persistence.jar
<SPRING_HOME>/lib/j2ee/jta.jar
I hope now it runs ok
Do not forget include MySQL driver if you do not want to see a new exception