JavaMailSender returning null pointer exception - spring

I am trying to send a register confirmation email in my spring MVC web application and Tomcat 7 using JavaMailSender but it always returns a NullPointerException. Can anyone help me find out why I get the null pointer? Below are my config settings:
web.xml
<!-- jndi mail session -->
<resource-ref>
<description>
Resource reference to a factory for javax.mail.Session
instances that may be used for sending electronic mail
messages, preconfigured to connect to the appropriate
SMTP server.
</description>
<res-ref-name>mail/Session</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>
application-servlet.xml
<!-- Mail Sender bean definition -->
<bean id="smtpSession" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/mail/session"/>
</bean>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="session" ref="smtpSession"/>
<!--
<property name="host" value="smtp.gmail.com" />
<property name="port" value="465" />
<property name="username" value="abc#gmail.com" />
<property name="password" value="test123" />
<property name="protocol" value="smtp" />
<property name="defaultEncoding" value="UTF-8"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.connectiontimeout">5000</prop>
<prop key="mail.smtp.sendpartial">true</prop>
<prop key="mail.smtp.userset">true</prop>
<prop key="mail.mime.charset">UTF-8</prop>
<prop key="mail.smtp.isSecure">true</prop>
<prop key="mail.smtp.requiresAuthentication">true</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.port">465</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
-->
</bean>
<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="abc#hotmail.com"/>
</bean>
context.xml (in tomcat conf folder)
<Context path="/MVC" docBase="MVC" debug="5" crossContext="false">
<Resource name="mail/session"
auth="Container"
type="javax.mail.Session"
username="abc#gmail.com"
password="test23"
mail.debug="true"
mail.user="abc#gmail.com"
mail.password="test123"
mail.transport.protocol="smtp"
mail.smtp.host="smtp.gmail.com"
mail.smtp.auth="true"
mail.smtp.port="25"
mail.smtp.starttls.enable="true"
/>
SendMail.java
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import com.wbkit.mvc.domain.User;
#Service
public class SendMail
{
#Autowired
private JavaMailSender mailSender;
#Autowired
private SimpleMailMessage simpleMailMessage;
public void confirmRegistrationMail(User user)
{
MimeMessage message = mailSender.createMimeMessage();
try
{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(user.getEmail());
helper.setSubject("MVC Registration");
helper.setText("Hello " + user.getFirstName() + " "
+ user.getLastName() + ", \n" +
" Your MVC Account Registration was successful. Your user ID is "
+ user.getEmail() + " and your password is "
+ user.getUserPass() + ".\n" +
"You can now access the mobile applicatoin or the web application "
+ " your user name (email) and password.");
}
catch (MessagingException e)
{
throw new MailParseException(e);
}
mailSender.send(message);
}
public void requireApprovalMail(final User user)
{
}
}
Stack Trace:
4-Sep-2012 7:47:16 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [MVC] in context with path [/MVC] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.wbkit.mvc.util.SendMail.confirmRegistrationMail(SendMail.java:79)
at com.wbkit.mvc.web.main.RegisterController.save(RegisterController.java:276)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1812)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException at com.wbkit.mvc.util.SendMail.confirmRegistrationMail(SendMail.java:79) points to
MimeMessage message = mailSender.createMimeMessage();
in SendMail.java. I removed some of the commented code I had.
Thanks for your suggestions and help.

I've had the same error. It came from a manual instantiation of the class that had the JavaMailSender bean as an autowired field. In the code posted by the OP, that would be the SendMail service class.
This question shed some light on the phenomenon: the autowired fields of the manually created object did not receive any actual reference to the JavaMailSender bean because Spring can't know it is supposed to do its magic then. It's very obvious afterwards.
Hope this helps someone.

It seems that you've included everything except the details of your exception.
Also, it looks like you're just making up property names. A bunch of the properties in your configuration are not valid JavaMail properties. Also, see this list of common mistakes.

Check your logging when the application starts up and see if you can see the JavaMailSender being wired into SendMail. You may have to set the org.springframework logging to DEBUG.
It seems to me that your wiring must be wrong, though I can't see why yet.

Remove the #Autowired from SimpleMailMessage and create the object of it inside confirmRegistrationMail() method:
public void confirmRegistrationMail(User user) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
}
This is probably because it's recommended to use the #Autowire for interface. e.g. JavaMailSender

Write #Service annotation on your helper class in which you have done the autowiring. And then use the #autowire annotation in the class where you are using that class.

Related

java.lang.ClassCastException: com.sun.proxy.$Proxy62 cannot be cast to org.hibernate.engine.spi.SessionImplementor

I'm having an issue with Spring and Hibernate Search. Here is my code:
#Slf4j
#Repository
public class DefaultIndexBuilderDao implements IndexBuilderDao {
#PersistenceContext
#Getter
#Setter
private EntityManager entityManager;
#Override
public void rebuildIndex() {
try {
log.debug("Starting the reindex process...");
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());
fullTextEntityManager.createIndexer().startAndWait();
log.debug("Reindex complete.");
} catch( InterruptedException e ) {
log.warn("Error rebuilding index: {}", e.getMessage(), e);
}
}
}
I'm getting:
Caused by: java.lang.ClassCastException: com.sun.proxy.$Proxy62 cannot be cast to org.hibernate.engine.spi.SessionImplementor
at org.hibernate.search.impl.FullTextSessionImpl.<init>(FullTextSessionImpl.java:62)
at org.hibernate.search.impl.ImplementationFactory.createFullTextSession(ImplementationFactory.java:35)
at org.hibernate.search.Search.getFullTextSession(Search.java:45)
at com.domainwww.dao.DefaultIndexBuilderDao.rebuildIndex(DefaultIndexBuilderDao.java:38)
at com.domainwww.service.DefaultIndexBuilderService.rebuildIndex(DefaultIndexBuilderService.java:30)
at com.domainwww.beans.admin.IndexBean.reindex(IndexBean.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 57 more
Here are the versions from my POM (properties) (in case this is a version conflict)
<spring.version>5.3.1</spring.version>
<hibernate.version>5.4.24.Final</hibernate.version>
<hibernate.search.version>5.11.7.Final</hibernate.search.version>
Here is by bean for entityManager:
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="net.xxxx,com.xxxx.dbmanager3.settings" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.dialect.storage_engine">innodb</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<prop key="hibernate.search.default.directory_provider">filesystem</prop>
<prop key="hibernate.search.default.indexBase">/opt/xxx/lucene/indexes</prop>
</props>
</property>
</bean>
So I get that Spring is injecting a Proxy, so how should I be obtaining the FullTextEntityManager, unwrapping seems to leave me with the same error? Thanks!
This is typically what happens when using Hibernate Search 5.11.5.Final and below with Spring boot 2.4 / Spring 5.3. See https://github.com/spring-projects/spring-framework/issues/26090
Given the ClassCastException occurs at FullTextSessionImpl.java:62, I suspect you are not actually using Hibernate Search 5.11.7.Final: in Hibernate Search 5.11.7.Final, this line is just an instanceof test. In 5.11.5.Final and below, this line actually is a cast.
I see you set property hibernate.search.version to 5.11.7.Final, but did you use this property anywhere in your POM? Spring Boot doesn't manage the dependency to Hibernate Search, so you need to specify the version yourself in your <dependency> markup.

Could not autowire field: private org.springframework.mail.javamail.JavaMailSender [Spring 4.0.0 REALEASE]

I tried to create a HTML mail sender in my application but i got this error. Here's my configuration using name space:
<?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"
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">
<context:property-placeholder location="classpath*:/mail_server.properties" />
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSender">
<property name="host" value="${host}"/>
<property name="port" value="${port}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
</beans>
Then i imported it into applicationContext.xml file in Spring project. In java class i just write a method to send HTML mail.
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.inject.Inject;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Repository;
import fi.vietjob.bean.mail.Mail;
#Repository
public class mailFeature {
#Inject
private JavaMailSender mailSender;
public JavaMailSender getMailSender() {
return mailSender;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void getPalaute(Mail mail, String to) {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject(mail.getSubject());
message.setText(mail.getText());
message.setFrom(mail.getFrom());
message.setSentDate(new Date());
mailSender.send(message);
}
public void sendHTMLEmail(Mail mail, String to, String senderName) {
try {
MimeMessage mime = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mime, true);
helper.setFrom(mail.getFrom(), senderName);
helper.setText(mail.getText());
helper.setSubject(mail.getSubject());
helper.setSentDate(new Date());
helper.setTo(to);
mailSender.send(mime);
} catch (MailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And when i run it, i got the stackstrace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mailFeature': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.mail.javamail.JavaMailSender fi.vietjob.feature.mailFeature.mailSender; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.mail.javamail.JavaMailSender] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:643)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:606)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:657)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:525)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:466)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4969)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
In your XML file you created the mail sender in this way:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSender">
<property name="host" value="${host}"/>
<property name="port" value="${port}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
So spring create a bean with id mailSender
When you try to inject it in your Repository, you simply use #Inject; try to use #Inject and #Qualifier
So try to write:
#Repository
public class mailFeature {
#Inject
#Qualifier("mailSender")
private JavaMailSender mailSender;
....
}
It should work
I hope it's useful
Angelo

JTA-Transactions - Mismatch between Spring and Hibernate connection release?

Versions in use:
Spring 4.1.6.RELEASE, Hibernate 4.3.10.Final, Atomikos 3.9.26
We are in the process of upgrading our main webapp to Hibernate 4. We mainly use HibernateTemplate and JdbcTemplate for access to multiple databases (DB2 and Oracle) with Atomikos as JTA-TransactionManager.
The problem: While using only HibernateTemplate or only JdbcTemplates in a single transaction works fine, using JdbcTemplate and HibernateTemplate together in one transaction causes StaleStateExceptions in certain cases.
Here is an example where the problem occurs - the code is wrapped in a TransactionalProxyFactoryBean with PROPAGATION_REQUIRED:
public class MyServiceImpl extends HibernateDaoSupport implements MyService {
private static final Log log = LogFactory.getLog(MyServiceImpl.class);
private JdbcTemplate jdbcTemplate;
#Override
public void execute() {
// save new entity instance with HibernateTemplate
MyEntity e = new MyEntity();
e.setMyProperty("first value");
getHibernateTemplate().save(e);
// use JdbcTemplate to access DB
String sql = "select * from my_table";
getJdbcTemplate().query(sql, new RowCallbackHandler() {
#Override
public void processRow(ResultSet rs) throws SQLException {
// process rows
}
});
// update entity instance with HibernateTemplate
e.setMyProperty("second value");
getHibernateTemplate().saveOrUpdate(e);
// make sure the flush occurs immediately. This is needed in to demonstrate the problem. (Otherwise the property UPDATE would be cached and issued on commit, just after Spring closed the connection used for the JdbcTemplate and the problem would not show)
getHibernateTemplate().flush();
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
Our conclusions: The exception is basically caused by different ways HibernateTemplate and JdbcTemplate accquire and release the database connection.
The HibernateTemplate directly delegates to Hibernate which uses the connection release mode AFTER_STATEMENT (set by Spring if a JtaTransactionManager is provided). This causes Hibernate to get a connection from the Atomikos connection pool, perform the SQL and close its connection which doesn't close the physical connection but returns it to the connection pool.
The JdbcTemplate uses Spring's DataSourceUtils.getConnection(...) to get a connection from the Atomikos connection pool, performs the SQL and calls DataSourceUtils.releaseConnection(...) which itself doesn't call Connection.close(). The connection isn't closed by Spring in DataSourceUtils.releaseConnection(...) (and in consequence not returned to the connection pool) but bound to the thread for reuse in DataSourceUtils.getConnection(...).
So it seems as if in a JTA context, Spring teaches Hibernate to use connection release mode AFTER_STATEMENT (which is also recommeded by Hibernate for JTA) but behaves totally different in it's DataSourceUtils.
In detail, we tracked down the cause like following:
The StaleStateException is thrown because the UPDATE-Statement for setting "second value" at the entity does not affect any row in the database.
This is because the UPDATE-Statement happens on another connection than the INSERT-Statement.
This is because the original connection used by the INSERT-Statement is still considered in use by the connection pool.
This is because close() is never called on the first connection after it was used for the JdbcTemplate.
This is because DataSourceUtils.releaseConnection(...) which is called by the JdbcTemplate when finished doesn't call Connection.close() in a JTA-Transaction-Context.
Things we tried and failed at:
Make Hibernate use AFTER_TRANSACTION or ON_CLOSE as connection release mode - prevented by Spring as SpringJtaSessionContext with it's AFTER_STATEMENT is hardcoded.
Configure Spring close the DB connection on connection release.
What are we doing wrong?
Any configuration we forgot?
Is it a Spring/Hibernate problem at all or should the Atomikos connection pool behave differently by not waiting for a call to Connection.close() before making the connection available again?
Thanks a lot for your help!
Spring context for Hibernate and JTA configuration:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="jtaTransactionManager" ref="transactionManager" />
<property name="hibernateProperties">
<props>
<!-- Stripped down configuration for the toy project to reproduce the problem -->
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.dialect">com.company.DB2Dialect</prop>
<!-- hibernate.transaction.factory_class and hibernate.transaction.jta.platform are implicitly set by setting the jtaTransactionManager property -->
<!-- Properties wie normally use in production
<prop key="hibernate.dialect">com.company.DB2Dialect</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.order_inserts">true</prop>
<prop key="hibernate.order_updates">true</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.use_outer_join">true</prop>
<prop key="hibernate.jdbc.batch_versioned_data">true</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
<prop key="hibernate.jdbc.batch_size">100</prop> -->
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath*:**/*.hbm.xml</value>
</list>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter"
scope="singleton">
<property name="targetDataSources">
<map>
<entry key="ISOLATION_REPEATABLE_READ" value="java:comp/env/jdbc/wawi_rr" />
<entry key="ISOLATION_READ_UNCOMMITTED" value="java:comp/env/jdbc/wawi_ru" />
<entry key="ISOLATION_READ_COMMITTED" value="java:comp/env/jdbc/wawi_rc" />
<entry key="ISOLATION_SERIALIZABLE" value="java:comp/env/jdbc/wawi_s" />
</map>
</property>
<property name="defaultTargetDataSource" value="java:comp/env/jdbc/wawi" />
</bean>
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName">
<value>java:comp/env/TransactionManager</value>
</property>
<property name="allowCustomIsolationLevels">
<value>true</value>
</property>
</bean>
Spring context for Service configuration:
<bean id="myService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="target">
<ref bean="myServiceTarget" />
</property>
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop>
</props>
</property>
</bean>
<bean id="myServiceTarget" class="org.example.MyServiceImpl">
<property name="sessionFactory" ref="sessionFactory" />
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="myMBean" class="org.example.MyMBean">
<property name="myService" ref="myService" />
</bean>
Stacktrace:
org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:205)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:343)
at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
at org.springframework.orm.hibernate4.HibernateTemplate.flush(HibernateTemplate.java:837)
at org.example.MyServiceImpl.execute(MyServiceImpl.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy13.execute(Unknown Source)
at org.example.MyMBean.execute(MyMBean.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:75)
at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:279)
at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1245)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1239)
at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:1077)
at org.springframework.jmx.export.SpringModelMBean.invoke(SpringModelMBean.java:90)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1420)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:556)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:811)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:670)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:63)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3281)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3183)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3525)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:159)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.springframework.orm.hibernate4.HibernateTemplate$27.doInHibernate(HibernateTemplate.java:840)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
... 54 more

HibernateTemplate showing java.lang.NullPointerException on using find() function

I am very new to Spring+Hibernate and am working on a very basic web project. Simple form is used and has two fields username and password. It has a submit button. When clicking on submit I am supposed to check if username and password exists in the database or not.This is my AuthenticationService Class
package com.service;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
#Service
public class AuthenticateService{
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.hibernateTemplate=new HibernateTemplate(sessionFactory);
}
public boolean verifyUsernameAndPassword(String username,String password)
{
System.out.println("Into the Service Class");
boolean userStatus=false;
try
{
List userObj = hibernateTemplate.find("from user u where u.username=? and u.password=?",username,password);
if(userObj.size()!=0)
{
userStatus=true;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return userStatus;
}
}
This is my bean configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/springmvc"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<!-- org.springframework.orm.hibernate3.LocalSessionFactoryBean -->
<bean id="sessionFactoryBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="mappingResources">
<value>com/pojo/user.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactoryBean"></property>
</bean>
<bean id="authenticateServiceBean" class="com.service.AuthenticateService">
<property name="hibernateTemplate" ref="hibernateTemplateBean"></property>
</bean>
</beans>
This is my Login Controller:
package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.service.AuthenticateService;
#Controller
#RequestMapping("/login.spring")
public class LoginController {
#Autowired
AuthenticateService authenticateService;
#RequestMapping(method= RequestMethod.POST)
public ModelAndView processCredentials(#RequestParam("username")String username ,#RequestParam("password")String password)
{
System.out.println("Inside username"+username + " password"+password);
String message="Invalid Credentials";
if(authenticateService.verifyUsernameAndPassword(username, password)==true)
{
message="Welcome"+username;
}
return new ModelAndView("results","message",message);
}
}
When I run the application I get the following stacktrace :
java.lang.NullPointerException
at com.service.AuthenticateService.verifyUsernameAndPassword(AuthenticateService.java:31)
at com.controller.LoginController.processCredentials(LoginController.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
I am sure the application goes to the Service class as I have printed the "Inside the Service Class". I don't know why its giving me a NullPointer.
You have two beans of type "com.service.AuthenticateService" one via annotation another in xml file.
The one defined via annotation is not provided hibernate template reference, hence null.
The one defined in xml is having proper reference but is not the one that gets injected.
Hope this helps.

load application context for junit hibernate tests inside spring

I've got a properly defined spring configuration XML file, which imports some other XML files. THe test should read/write/delete records from MySQL database. I've got a problem with hibernate - the test is unable to access the database and hibernate throws following exception:
Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor];
nested exception is org.hibernate.service.UnknownServiceException:
Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]
This is my test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(value = "classpath:*.xml")
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#Transactional
public class JukeboxTest {
#Autowired
private ApplicationContext applicationContext;
private Jukebox jukebox;
private SessionFactory sessionFactory;
private Session session = null;
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
jukebox = (Jukebox) applicationContext.getBean("metal_jukebox");
sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
session = sessionFactory.openSession();
System.out.println(jukebox.getName());
}
#After
public void tearDown() {
session.close();
sessionFactory.close();
}
#Test
#Transactional
public void testGetName() {
assertEquals("Metal Jukebox", jukebox.getName());
}
This is my hibernate config file:
<?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"
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.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.blogspot.symfonyworld.lyricsbase.model.Song</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
the system.out line properly displays value defined in the bean XML, so the configuration is ok. I guess the annotations are somehow wrong, but I don't know what to fix, since the exception tells me nothing.
This is the exception stack trace:
org.springframework.orm.hibernate4.HibernateSystemException: Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]; nested exception is org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:185)
at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:594)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:495)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:846)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:823)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:588)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:297)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:192)
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:396)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:91)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:126)
at org.hibernate.internal.SessionFactoryImpl.getStatisticsImplementor(SessionFactoryImpl.java:1468)
at org.hibernate.internal.SessionFactoryImpl.getStatistics(SessionFactoryImpl.java:1464)
at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.afterTransaction(TransactionCoordinatorImpl.java:140)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.afterTransactionCompletion(JdbcTransaction.java:138)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:214)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:488)
... 33 more
Please define the bean JukeBox in the test context if this is a service.
If this is dao then please inject the entitymanager, transaction manager and session factory to the bean.

Resources