Green test is failing when is launched by maven - java

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.

Related

Inject 2 (3 in the near future) different entityManagerFactory (or entityManager) in spring application

I have Spring + JPA (Hibernate) project, at which i connect to MsSQL database, now i need to open a new connection but this time it will be for MySQL.
i am using XML configuration
<bean id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${spring.datasource.driverClassName}" />
....
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:packagesToScan="com.wsg.admin.api.model"
p:jpaVendorAdapter-ref="hibernateJpaVendorAdapter">
<property name="jpaProperties">
<props>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
....
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Configure the MySQL connection -->
<bean id="enduserDataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${enduser.db.driver}" />
....
</bean>
<bean id="enduserEntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="enduserDataSource" p:packagesToScan="com.wsg.admin.api.model"
p:jpaVendorAdapter-ref="hibernateJpaVendorAdapter">
<property name="jpaProperties">
<props>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
....
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="enduserTransactionManager" />
<bean id="enduserTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="enduserEntityManagerFactory" />
</bean>
then i try to inject the entityManager using the fragment
#Autowired
EntityManager entityManager;
but i get exception
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'brandServiceImpl': Unsatisfied dependency expressed through field 'entityManager'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManager' available: expected single matching bean but found 2: org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
Since you have two Entity Manager's(From EntityMangaerFactory) you need to tell spring which specifix EntityManager you want to be Autowired. Use #Qualifier
#Autowired
#Qualifier("enduserEntityManagerFactory") // use bean id of the Entity Manager Factory you want to inject
EntityManagerFactory entityManagerFactory
EntityManager entityManager = entityManagerFactory.createEntityManager();
More about this here
Fixed. Thanks to #Volceri
i used the answer https://stackoverflow.com/a/18073628/1973933, as follow
add <property name="persistenceUnitName" value="appPU" /> to each of entityManagerFactory
<bean id="entityManagerFactory" ... >
<property name="jpaProperties">
<props>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
...
</props>
</property>
<property name="persistenceUnitName" value="dataSourcePU" />
</bean>
<bean id="endUserEntityManagerFactory" ... >
<property name="jpaProperties">
<props>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
...
</props>
</property>
<property name="persistenceUnitName" value="enduserDataSourcePU" />
</bean>
and to inject the em objects, i used
#PersistenceContext(unitName="dataSourcePU")
EntityManager entityManager;
#PersistenceContext(unitName="enduserDataSourcePU")
EntityManager endUserEntityManager;

File not found Exception in Spring annotation integration with hibernate

I'm using hibernate integrated with Spring annotation and getting FileNotFoundException for my Entity class
This is my applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<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:3306/db1"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>vendors.Vendor</value>
<value>accountBooks.DayBookData</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="vendor" class="vendors.VendorDao">
<property name="hibernateTemplate" ref="template"></property>
</bean>
<bean id="dayBook" class="accountBooks.DayBookDao">
<property name="hibernateTemplate" ref="template"></property>
</bean>
</beans>
My Dao class
public class DayBookDao {
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public void saveDayBookData(DayBookData dayBook){
hibernateTemplate.save(dayBook);
}
public void updateDayBookData(DayBookData dayBook){
hibernateTemplate.update(dayBook);
}
public void deleteDayBookData(DayBookData dayBook){
hibernateTemplate.delete(dayBook);
}
public List<DayBookData> getDayBookData(){
List<DayBookData> dayBook = hibernateTemplate.loadAll(DayBookData.class);
return dayBook;
}
}
My Main class
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource r = new ClassPathResource("applicationContext.xml");
BeanFactory bean = new XmlBeanFactory(r);
DayBookDao dayBookDao = (DayBookDao) bean.getBean("dayBook");
DayBookData dayBook = new DayBookData();
dayBook.setAccountType("Bank Account");
dayBook.setTransType("Receipt");
dayBook.setOppAccount("Profit-Loss");
dayBook.setAmount(15000);
dayBook.setTransDate(new Date());
dayBookDao.saveDayBookData(dayBook);
}
I'm getting error
**Caused by: java.io.FileNotFoundException: class path resource [vendors.Vendor] cannot be opened because it does not exist
Property mappingResources are used for XML (hbm.xml) mapping.
Hibernae 4 and above
You just need to put all your persistent classes to the some.package.model package and use
<property name="packagesToScan" value="some.package.model" />
to add all classes from that package. Inner packages are processed as well.
Also you can add persistent classes separately using
<property name="annotatedClasses">
<list>
<value>vendors.Vendor</value>
<value>accountBooks.DayBookData</value>
</list>
</property>
Hibernate 3
Hibearnate 3 configuration using annotated persistent classes and Spring a bit more complex.
It is need to add persistent classes to the hibernate.cfg.xml and configure Spring by this way:
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
</bean>
Hibernate 3 uses a separate config class for configurations with annotations:
org.hibernate.cfg.AnnotationConfiguration

Hibernate 4 + Spring : org.springframework.beans.factory.BeanCreationException

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>

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.

Error creating bean with name 'sessionFactory'

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

Categories

Resources