Velocity email template in /WEB-INF subfolder - spring

I coded service to send email. Now I have to integrate velocity freamwork and so I edit my mail-context.xml
....
<bean id="mailService" class="xxx.xxxx.xxxx.service.MailServiceImpl">
<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="customeMailMessage" />
<property name="velocityEngine" ref="velocityEngine" />
</bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="resource.loader">webapp</prop>
<prop key="webapp.resource.loader.class">org.apache.velocity.tools.view.WebappResourceLoader</prop>
<prop key="webapp.resource.loader.path">/WEB-INF/email</prop>
</props>
</property>
</bean>
...
And I put in /WEB-INF/email my template file .vm
This is my mail service
#Service("MailService")
#Transactional
public class MailServiceImpl implements MailService {
private JavaMailSender mailSender;
private VelocityEngine velocityEngine;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
.....
public void sendEmailVelocity(final Userprofile userprofile) throws MessagingException, IOException {
System.out.println("Sending mail...");
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
Map model = new HashMap();
model.put("user", userprofile);
helper.setFrom("info#spidly.com");
helper.setTo("claudio.pomo#gmail.com");
helper.setSubject("velocity");
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "test.vm", model);
helper.setText(text, true);
mailSender.send(message);
System.out.println("Mail sent!");
}
...
And then the stack trace is
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'test.vm'
at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:343)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:320)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplate(VelocityEngineUtils.java:58)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplateIntoString(VelocityEngineUtils.java:122)
at xx.xxxxxxx.xxx.service.MailServiceImpl.sendEmailVelocity(MailServiceImpl.java:410)
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:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy61.sendEmailVelocity(Unknown Source)org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'test.vm'
at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:343)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:320)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplate(VelocityEngineUtils.java:58)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplateIntoString(VelocityEngineUtils.java:122)
at xx.xxxxx.xxxx.service.MailServiceImpl.sendEmailVelocity(MailServiceImpl.java:410)
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:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy61.sendEmailVelocity(Unknown Source)
Any suggestion?

Change your velocityEngine bean to
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/email/" />
</bean>
and it should work.

Related

how can we build a spring mvc multitenant application using hibernate as orm separate database and schema

from spring io u shifted to stack overflow but nowhere u have explained about multitenant complete demo application which can be seen as a problem solver infact no one seen satisfied with ur answers can u please now share a working demo of multitenant schema and separate database complete code anywhere where people can use it kindly
package com.domain.model;
import javax.persistence.*;
#Entity
#Table
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int employeeId;
#Column
private String employeeName;
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
}
package com.domain.multitenancy;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class CurrentTenantIdentifierResolverimpl implements CurrentTenantIdentifierResolver {
#Override
public String resolveCurrentTenantIdentifier() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String tenantId = attr.getRequest().getParameter("tenantId");
return tenantId;
}
#Override
public boolean validateExistingCurrentSessions() {
return true;
}
}
package com.domain.multitenancy;
import com.domain.master.MasterService;
import org.hibernate.service.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl;
import javax.sql.DataSource;
public class MultiTenantConnectionprovideImpl extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
#Override
protected DataSource selectAnyDataSource() {
return MasterService.getDataSourceHashMap().get("tenantId1");
}
#Override
protected DataSource selectDataSource(String tenantIdentifier) {
return MasterService.getDataSourceHashMap().get(tenantIdentifier);
}
}
package com.domain.master;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
public class MasterService {
public static HashMap<String, DataSource> getDataSourceHashMap() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/multiten");
dataSource.setUsername("root");
dataSource.setPassword("root");
DriverManagerDataSource dataSource1 = new DriverManagerDataSource();
dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
dataSource1.setUrl("jdbc:mysql://localhost:3306/multiten_1");
dataSource1.setUsername("root");
dataSource1.setPassword("root");
HashMap hashMap = new HashMap();
hashMap.put("tenantId1", dataSource);
hashMap.put("tenantId2", dataSource1);
return hashMap;
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.domain"/>
<mvc:annotation-driven/>
<context:property-placeholder location="classpath:application.properties"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
<property name="packagesToScan">
<list>
<value>com.domain.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
<prop key="hibernate.multiTenancy">DATABASE</prop>
<prop key="hibernate.tenant_identifier_resolver">com.domain.multitenancy.CurrentTenantIdentifierResolverimpl</prop>
<prop key="hibernate.multi_tenant_connection_provider">com.domain.multitenancy.MultiTenantConnectionprovideImpl</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
#Application.properties file in classpath
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/multiten
jdbc.username = root
jdbc.password = root
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql = true
hibernate.format_sql = false
I have taken this example
these are the errors i got:
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
org.hibernate.HibernateException: SessionFactory configured for
multi-tenancy, but no tenant identifier specified
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is
org.hibernate.HibernateException: SessionFactory configured for
multi-tenancy, but no tenant identifier specified
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
com.sun.proxy.$Proxy22.save(Unknown Source)
com.domain.controller.EmployeeController.saveEmployee(EmployeeController.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hibernate.HibernateException: SessionFactory configured for multi-tenancy, but no tenant identifier specified
org.hibernate.internal.AbstractSessionImpl.(AbstractSessionImpl.java:85)
org.hibernate.internal.SessionImpl.(SessionImpl.java:239)
org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1618)
org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:978)
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:436)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
com.sun.proxy.$Proxy22.save(Unknown Source)
com.domain.controller.EmployeeController.saveEmployee(EmployeeController.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Session for transaction; nested exception is
org.hibernate.HibernateException: SessionFactory configured for
multi-tenancy, but no tenant identifier specified
The above error suggests that tenant identifier is not specified. Please double check your configuration and the identifier class implementation name.
The reason you are getting this error is that your tenant identifier resolver needs to return something default in case it cannot find appropriate tenant id from the strategy you have chosen ( in your case you are trying to get the tenant id from request params). I have used the updated code below and it is no longer showing the error.
public class CurrentTenantIdentifierResolverimpl implements CurrentTenantIdentifierResolver {
#Override
public String resolveCurrentTenantIdentifier() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String tenantId = attr.getRequest().getParameter("tenantId");
if (tenantId==null) {
//return default tenant
return "tenantId1";
}
return tenantId;
}
#Override
public boolean validateExistingCurrentSessions() {
return true;
}
}
Shailendra sir how can we set a tenant id to it without setting default id and get the username from spring security and pass it to the tenant id

How to solve NullPointerException at mailSender when using some organization as a host

I'm trying to send emails using an organisation mailSender.
Controller
#RequestMapping(value="/forgetPassword", method = RequestMethod.POST, consumes={"application/json"})
public #ResponseBody User forgetPassword(#RequestBody User user) throws Exception {
user=userService.forgetPassword(user, newPassword);
if(user !=null)
{
SendEmail callsendEmail = new SendEmail();
callsendEmail.emailSender(user);
return user;
}
else
{
return user;
}
}
SendEmail
public class SendEmail {
private JavaMailSender mailSender;
private VelocityEngine velocityEngine;
private SimpleMailMessage templateMessage;
public void emailSender(final User user) throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.setFrom(templateMessage.getFrom());
message.setTo(user.getEmail());
message.setSubject(templateMessage.getSubject());
Map<String, User> model = new HashMap<String, User>();
model.put("user", user);
/*String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "org/utility/mailTemplate.vm", model);
message.setText(text, true);*/
if (mailSender != null) {
mailSender.send(mimeMessage);
}
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public SimpleMailMessage getTemplateMessage() {
return templateMessage;
}
public void setTemplateMessage(SimpleMailMessage templateMessage) {
this.templateMessage = templateMessage;
}
}
Configuration
<bean id="emailSender" class="org.utility.SendEmail">
<property name="mailSender" ref="mailSender" />
<property name="velocityEngine" ref="velocityEngine" />
<property name="templateMessage" ref="templateMessage" />
</bean>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="10.6.12.229" />
<property name="port" value="25" />
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>resource.loader=class class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</value>
</property>
</bean>
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="noreply#scrumtracker.com" />
<property name="subject" value="Scrum Tracker Login Details" />
</bean>
Here's the stack trace:
SEVERE: Servlet.service() for servlet [spring] in context with path [/OLPV] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.utility.SendEmail.emailSender(SendEmail.java:24)
at org.controller.UserController.forgetPassword(UserController.java:125)
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.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
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:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:119)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:242)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:201)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:163)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:556)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:401)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I'm getting nullpointer exception on running the above code. Data is passing to the SendEmail class from Controller. Any idea on this?
Set #autowired from calling class (Don't do New) to the mailSend class.
Write #Service in mailSend class.
Directly call the mailSend.Send() method from the calling class.
All prop will be set automatically. No null point exception.
Namaste !
In your Controller class you don't need to instantiante the SendEmail like you do
SendEmail callsendEmail = new SendEmail();
But instead inject it as a spring bean
#Controller
class MyController {
#Autowired
private SendEmail callsendEmail;
#RequestMapping(value="/forgetPassword", method = RequestMethod.POST, consumes={"application/json"})
public #ResponseBody User forgetPassword(#RequestBody User user) throws Exception {
user=userService.forgetPassword(user, newPassword);
if(user !=null)
{
callsendEmail.emailSender(user);
return user;
}
else
{
return user;
}
}
}
If your application context is not configured to autowire beans by annotations, then use a regular setter in the class
#Required
public void setSendEmail( SendEmail sendEmail ) {
this.callsendEmail = sendEmail;
}

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I have problem with session in hibernate, below is the error trace:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:574)
at ptv.generic.dao.AbstractGenericSearchDaoHibernateImpl.findByQuery(AbstractGenericSearchDaoHibernateImpl.java:327)
at ptv.generic.dao.AbstractGenericSearchDaoHibernateImpl.findByQuery(AbstractGenericSearchDaoHibernateImpl.java:311)
at ptv.drm.dao.impl.RightsProfileHibernateDao.findByLookupName(RightsProfileHibernateDao.java:93)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy50.findByLookupName(Unknown Source)
at ptv.media.ingest.processor.CmsXMLIngestUpdateServiceImpl.verifyProfilesRightsRelation(CmsXMLIngestUpdateServiceImpl.java:1104)
at ptv.media.ingest.processor.CmsXMLIngestUpdateServiceImpl.addNewMediaContent(CmsXMLIngestUpdateServiceImpl.java:659)
at ptv.media.ingest.processor.CmsXMLIngestUpdateServiceImpl.insert(CmsXMLIngestUpdateServiceImpl.java:296)
at ptv.media.ingest.processor.AbstractCmsXMLIngestFileStrategy.insertNewMediaContent(AbstractCmsXMLIngestFileStrategy.java:251)
at ptv.media.ingest.processor.CmsXMLIngestFileUnencodedStrategy.insert(CmsXMLIngestFileUnencodedStrategy.java:74)
at ptv.media.autoingest.service.AutoIngestServiceImpl.ingestObtainedFiles(AutoIngestServiceImpl.java:1661)
at ptv.media.autoingest.service.AutoIngestServiceImpl.process(AutoIngestServiceImpl.java:138)
at ptv.media.TestAutoIngest.main(TestAutoIngest.java:19)
applicationContext:
<bean id="drmDaoProxyCreator"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<description>Automatically wraps all the specified bean(s) with a
transaction layer
</description>
<property name="proxyTargetClass" value="false" />
<property name="beanNames">
<list>
<value>rightsProfileDAO</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>drmTxInterceptor</value>
</list>
</property>
</bean>
<bean id="drmTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<description>DRM transaction manager</description>
<property name="sessionFactory" ref="drmOwnerSessionFactory" />
</bean>
<bean id="drmTxInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<description>DRM transaction interceptor</description>
<property name="transactionManager" ref="drmTransactionManager" />
<property name="transactionAttributeSource">
<bean
class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean id="rightsProfileDAO" class="ptv.drm.dao.impl.RightsProfileHibernateDao">
<description>Data access object for accessing RIGHTS_PROFILE table
</description>
<property name="sessionFactory" ref="drmOwnerSessionFactory" />
</bean>
RightsProfileHibernateDao
/**
* {#inheritDoc}
*/
#Override
public RightsProfile findByLookupName(final String lookupName) {
final List<RightsProfile> result = findByQuery("from RightsProfile where lookupName = :lookupName", new String[] { "lookupName" },
new Object[] { lookupName });
return CollectionUtils.isEmpty(result) ? null : result.get(0);
}
Main method:
#Transactional
private Pair<String, Boolean> ingestObtainedFiles(final Integer orgnId) {
try {
folder = ftpAccountService.getMonitoringFolderByOrgnId(orgnId);
final List<File> clientsXMLFiles = scanFTPFolderForXmlFiles(new File(
folder.getProcessingDirectory()));
// Sort files, so they will be processed from oldest to newest.
// Added for AutoIngestService to work properly.
Collections.sort(clientsXMLFiles, new Comparator<File>() {
#Override
public int compare(final File file1, final File file2) {
return Long.valueOf(file1.lastModified()).compareTo(
file2.lastModified());
}
});
for (final File messageFile : clientsXMLFiles) {
LOGGER.debug("Processing file " + messageFile.getAbsolutePath());
final Assets assets = getIngestXMLUnMarshaler(messageFile);
// process it. Intercept it so we begin transaction.
getCmsXMLIngestFileUnencodedStrategy().insert(assets, folder, messageFile);
}
} catch (final Exception e) {
LOGGER.error("Error when ingesting files" ,e);
}
return new Pair<String, Boolean>(folder.toString(), true);
}
I already tried to add the #Transactional annotation to the service, to the dao almost everywhere.
Enable Annotation based Transaction Management in your Spring configuration file by adding<tx:annotation-driven/>.
Here is a good link which you can look into.

Spring-mvc error 505 while trying to get data from database using hibernate in dropdown menu

I am having difficulties while trying to launch my application, I am stuck somewhere in the code.
my entity class is:
#Entity
#Table(name="metalocation")
public class Location implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID")
private int id;
#Column(name="DB_ID")
private String dbId;
#Column(name="GEO_LAT")
private double geoLAT;
#Column(name="GEO_LNG")
private double geoLNG;
#Column(name="IN_LOCATION")
private int inLocation;
#Column(name="ISO")
private String iso;
#Column(name="LOCAL_NAME")
private String localName;
#Column(name="TYPE")
private char type;
#OneToMany(cascade=CascadeType.PERSIST)
#JoinColumn(name="meta_address_fk")
private Set<Address> address;
public Location() {
}
.......... All setters and getters
my Service interface is:
import java.util.List;
import com.platformhouse.clinicsystem.web.model.entity.Address;
import com.platformhouse.clinicsystem.web.model.entity.Location;
public interface AddressService {
public List<Location> getAllCountries();
}
my service class is:
#Service("adressService")
#Transactional
public class AddressServiceImplementation implements AddressService {
private AddressDAO addressDAO;
//
public void setPatientDao(AddressDAO addressDAO) {
this.addressDAO = addressDAO;
}
#Transactional
public List<Location> getAllCountries() {
return this.addressDAO.getAllCountries();
}
}
My DAO is:
#Repository
#Transactional
public class AddressDAO {
#Autowired
private SessionFactory session;
public void setSession(SessionFactory session) {
this.session = session;
}
public Session session(){
return session.getCurrentSession();
}
#SuppressWarnings("unchecked")
public List<Location> getAllCountries() {
Query query = session().createQuery("from Location where inLocation <=246");
List<Location> results = query.list();
return results;
}
}
my Controller is:
#Controller
#RequestMapping(value = "/usersignup")
public class PatientSignupController {
private PatientService patientService;
private AddressService addressService;
#RequestMapping(value = "/usersignup")
public String signup() {
return "usersignup";
}
#RequestMapping( method = RequestMethod.GET)
public List<Location> getCountries() {
return this.addressService.getAllCountries();
}
}
my hibernate xml:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<context:component-scan base-package="com.platformhouse.clinicsystem.web.dao">
</context:component-scan>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.platformhouse.clinicsystem.web.model.entity.User</value>
<value>com.platformhouse.clinicsystem.web.model.entity.UserType</value>
</value>
<value>com.platformhouse.clinicsystem.web.model.entity.Location
</value>
<
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="javax.persistence.validation.group.pre-persist">com.platformhouse.clinicsystem.web.validation.PersistenceValidationGroup
</prop>
<prop key="javax.persistence.validation.group.pre-update">com.platformhouse.clinicsystem.web.validation.PersistenceValidationGroup
</prop>
<prop key="javax.persistence.validation.group.pre-remove">com.platformhouse.clinicsystem.web.validation.PersistenceValidationGroup
</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.platformhouse.clinicsystem.web.dao</value>
<value>com.platformhouse.clinicsystem.web.service.implementation</value>
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="exceptionTranslator"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor">
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
my JSp code is:
<form method="Get">
<label>Country/region:</label>
<select id="iCountry" name="iCountry">
<c:forEach items="${locationList}" var="country">
<option selected="selected" value="">please select country</option>
<option value="${country.id}">${country.localName}</option>
</c:forEach>
<select />
my results are:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
**type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
----------
// controller error
com.platformhouse.clinicsystem.web.controller.PatientSignupController.getCountries(PatientSignupController.java:40)
----------
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
You have forgot to add #Autowired annotation for your services. Thats why you are getting NullPointerException. Please check below
#Autowired
private PatientService patientService;
#Autowired
private AddressService addressService;
Update
You have mentioned it as #Service("adressService"). addressService is not spelled correctly.
change it to #Service("addressService")

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