I'm getting the following exception on running a test case, for my service class.
javax.ejb.EJBException: No EJBContainer provider available: no provider names had been found.
at javax.ejb.embeddable.EJBContainer.reportError(EJBContainer.java:216)
at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:146)
at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:102)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Code:
public class NativeServiceTest {
static NativeService NativeService;
private static Context ctx;
private static EJBContainer ejbContainer;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
ejbContainer = EJBContainer.createEJBContainer();
ctx = ejbContainer.getContext();
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
ejbContainer.close();
}
#Test
public void testGetCustomService() throws NamingException {
Gson gson= new Gson();
String id = "";
NativeService converter = (NativeService) ctx.lookup("java:global/classes/NativeService");
assertNotNull(converter);
gson.fromJson(NativeService.getCustomService(id), Portlet.class);
}
}
NativeService.java
public class NativeService {
#EJB
DataService dataService;
//
//
}
I'm using jta-data-source for transaction.
NativeService needs to be an EJBBean, for example #Stateless. Also make sure the test is in the same project as the EJBBean.
Related
I'm writing some code to test a web service using mockito and junit, so I faced a problem within the hasSize(2). I have injected the controller and calling the method findAll which returns a list of Employees, but error persists, in debugging mode it told me that the collection was empty, however, it is not.
the error is:
java.lang.AssertionError: JSON path "$" Expected: a collection with
size <2> but: collection size was <0>
here is the class:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class GestionPointage3ApplicationTests {
private MockMvc mockMvc;
#InjectMocks
private EmployeController employeeController ;
#Mock
private EmployeService employeeService;
#Mock
private ModelMapper modelMapper;
#Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
mockMvc=MockMvcBuilders.standaloneSetup(employeeController).build();
}
#Test
public void testgetAllEmployeeWithModelMapper() throws Exception{
Employe emp1 = new Employe("Hamza", "Khadhri", "hamza1007", "123");
Employe emp2 = new Employe("Oussema", "smi", "oussama", "1234");
List<Employe> Employees= Arrays.asList(emp1, emp2);
EmployeDTO dto1 = new EmployeDTO("Hamza", "Khadhri", "hamza1007", "123");
EmployeDTO dto2 = new EmployeDTO("Oussema", "smi", "oussama", "1234");
//when(modelMapper.map(emp1,EmployeDTO.class)).thenReturn(dto1);
// when(modelMapper.map(emp2,EmployeDTO.class)).thenReturn(dto2);
when(employeeService.findAll()).thenReturn(Employees);
mockMvc.perform(get("/employe/dto"))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].nom", is("Hamza")))
.andExpect(jsonPath("$[0].prenom", is("Khadhri")))
.andExpect(jsonPath("$[0].login", is("hamza1007")))
.andExpect(jsonPath("$[0].mp", is("123")))
.andExpect(jsonPath("$[1].nom", is("Oussema")))
.andExpect(jsonPath("$[1].prenom", is("smi")))
.andExpect(jsonPath("$[1].login", is("oussama")))
.andExpect(jsonPath("$[1].mp", is("1234")));
verify(employeeService,times(1)).findAll();
verifyNoMoreInteractions(employeeService);
}
}
and this is the Controller:
#CrossOrigin(origins = "*", allowedHeaders = "*")
#RestController
#RequestMapping("/employe")
public class EmployeController {
#Autowired
private EmployeService employeService;
#Autowired
private ModelMapper modelMapper;
#GetMapping("/dto")
public List<Employe> findAll() throws Exception{
return employeService.findAllEmployeActive();
}
}
method signature:
public List<Employe>findAll() throws Exception;
public List<Employe>findAllEmployeActive() throws Exception;
StackTrace errors:
java.lang.AssertionError: Status expected:<200> but was:<500> at
org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at
org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at
org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at
org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at
com.cynapsys.pointage.GestionPointage3ApplicationTests.testgetAllEmployeeWithModelMapper(GestionPointage3ApplicationTests.java:66)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at
org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at
org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at..
You are mocking EmployeeService and telling the mocked instance to return the Employee list (with its two items) when the findAll() method is invoked:
when(employeeService.findAll()).thenReturn(Employees)
But in the EmployeeController you are actually invoking a different method on EmployeeService:
return employeService.findAllEmployeActive()
So, you should update your mocked expectation like so:
when(employeeService.findAllEmployeActive()).thenReturn(Employees)
I am trying to hold a member of an abstract class in a concrete class using hibernate.
My classes are
#Entity
#Table(name = "utente2")
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn
(
name="tipo_collocazione",
discriminatorType=DiscriminatorType.STRING
)
public abstract class Utente2 implements Serializable{
#Id
private Long idUtente;
#Column(name = "nome")
private String nome;
#Column(name = "cognome")
private String cognome;
#Column(name = "email")
private String email;
public Utente2() {}
public Long getIdUtente() {
return idUtente;
}
public void setIdUtente(Long idUtente) {
this.idUtente = idUtente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public abstract String getCollocazione();
}
#Entity
#DiscriminatorValue("INTERNO")
public class UtenteInterno extends Utente2 {
#Column(name = "collocazione")
private String collocazione;
public UtenteInterno(){
super();
}
#Override
public String getCollocazione() {
return "Collocazione interna: " + getCollocazione();
}
public void setCollocazione(String collocazione) {
this.collocazione = collocazione;
}
}
#Entity
#DiscriminatorValue("ESTERNO")
public class UtenteEsterno extends Utente2 {
#Column(name = "collocazione")
private String collocazione;
public UtenteEsterno(){
super();
}
#Override
public String getCollocazione() {
return "Collocazione esterna - indirizzo: " + getCollocazione();
}
public void setCollocazione(String collocazione) {
this.collocazione = collocazione;
}
}
and the final problem is
org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: : googleTest2.HelloGoogle3.entities.Utente2
at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:114)
at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:136)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.instantiate(AbstractEntityTuplizer.java:737)
at org.hibernate.persister.entity.AbstractEntityPersister.instantiate(AbstractEntityPersister.java:4761)
at org.hibernate.internal.SessionImpl.instantiate(SessionImpl.java:1427)
at org.hibernate.internal.SessionImpl.instantiate(SessionImpl.java:1415)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1619)
at org.hibernate.loader.Loader.getRow(Loader.java:1515)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:726)
at org.hibernate.loader.Loader.processResultSet(Loader.java:953)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1300)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:495)
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:71)
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 com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:130)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:362)
at com.sun.proxy.$Proxy38.getSingleResult(Unknown Source)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:202)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:97)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:88)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:395)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:373)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
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.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy30.findByNome(Unknown Source)
at googleTest2.HelloGoogle3.controller.HomeController.testDBjpa1_repo(HomeController.java:245)
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 com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:130)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:502)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
In the db I have table utente2 with 2 records. One with discriminator column "INTERNO" and one with disscrinator column "ESTERNO".
This configuration work well if, for example, I run the app with tomcat, but now I want to run it with google app engine...
When, in the controller, I make the request like
Utente2 utente = utenteRepo.findByNome("NameUtente");
I have the previous error...
Does it change something with this hibernate configuration when I run the app on google app engine + google cloy sql (mysql db) ?
thanks
The problem was that I missed to map class and subclasses in my persistence.xml.
I have some trouble when during writing a test class for getSession method in DAO
code below
Test class
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.when;
public class SessionDaoImplTest {
private SessionDaoImpl sessionDao;
#Mock
private SessionFactory session;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
sessionDao = new SessionDaoImpl(session);
}
#Test
public void testGetCurrentSession() throws Exception {
when(sessionDao.getCurrentSession()).
thenReturn(session.getCurrentSession());
}
}
under test class
import com.oleg.project.dao.Session.SessionDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class SessionDaoImpl implements SessionDao {
#Autowired
private SessionFactory sessionFactory;
SessionDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getCurrentSession() {
Session session = sessionFactory.getCurrentSession();
return session;
}
}
StackTrace
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.oleg.project.dao.Session.impl.
SessionDaoImplTest.testGetCurrentSession(SessionDaoImplTest.java:28)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
3: you are stubbing the behaviour of another mock inside before
'thenReturn' instruction if completed
at com.oleg.project.dao.Session.impl.SessionDaoImplTest.testGetCurrentSession(SessionDaoImplTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
The variable sessionDao is not a mock.
I think you meant sessionDao = spy(new SessionDaoImpl(session));
Edit:
Also you have to extract session.getCurrentSession() into a local variable:
Session currentSession = session.getCurrentSession();
when(sessionDao.getCurrentSession()).thenReturn(currentSession);
When I run this code it gives me the following exception:
com.sun.faces.application.view.FaceletViewHandlingStrategy
handleRenderException SCHWERWIEGEND: Error Rendering
View[/index.xhtml] java.lang.ClassCastException: Text cannot be cast
to java.lang.String.
I am using Primefaces 5.0 and JSF 2.2
index.xhtml
<body>
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Simple:" for="acSimple" />
<p:autoComplete id="acSimple" value="#{autoCompleteView.txt}"
completeMethod="#{autoCompleteView.completeText}" var="t" itemValue="#{t}"
itemLabel="#{t.query}" converter="#{TextConverter}">
<f:facet name="itemtip">
<h:panelGrid columns="2" cellpadding="5">
<span>Hello</span>
<h:outputText value="#{t.query}" />
<h:outputText value="#{t.id}" />
</h:panelGrid>
</f:facet>
</p:autoComplete>
</h:panelGrid>
</h:form>
</body>
Text.java
public class Text {
private String id;
private String query;
public String getId() {
return this.id;
}
public Text(final String id, final String query) {
this.id = id;
this.query = query;
}
public Text() {
this.id = "";
this.query = "";
}
public String setId(final String id) {
return this.id = id;
}
public String getQuery() {
return this.query;
}
public String setQuery(final String query) {
return this.query = query;
}
#Override
public String toString() {
return this.query;
}
}
TextConverter.java
#FacesConverter("TextConverter")
public class TextConverter implements Converter {
#ManagedProperty(value = "#{autoCompleteView}")
private AutoCompleteView A;
#Override
public Object getAsObject(final FacesContext context, final UIComponent component, final String value) {
for (final Text t : this.A.getResults()) {
if (t.getId().equals(value)) {
return t;
}
}
return null;
}
#Override
public String getAsString(final FacesContext context, final UIComponent component, final Object value) {
// TODO Auto-generated method stub
if (value instanceof Text) {
final Text t = (Text) value;
return t.toString();
}
return "";
}
}
AutoCompleteView.java
#ManagedBean
#SessionScoped
public class AutoCompleteView {
private String txt;
private List<Text> Texts;
private Text t = null;
private List<Text> results;
public List<Text> getTexts() {
return this.Texts;
}
public void setTexts(final List<Text> texts) {
this.Texts = texts;
}
public List<Text> completeText(final String txt) {
this.results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final String id = "" + i;
final String s = txt + i;
this.t = new Text(id, s);
System.out.println(this.t);
this.results.add(this.t);
}
return this.results;
}
public String getTxt() {
return this.txt;
}
public void setTxt1(final String txt) {
this.txt = txt;
}
public List<Text> getResults() {
return this.results;
}
public void setResults(final List<Text> results) {
this.results = results;
}
}
Error
com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SCHWERWIEGEND: Error Rendering View[/index.xhtml]
java.lang.ClassCastException: Text cannot be cast to java.lang.String
at org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeSuggestionsAsList(AutoCompleteRenderer.java:497)
at org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeSuggestions(AutoCompleteRenderer.java:393)
at org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeResults(AutoCompleteRenderer.java:123)
at org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeEnd(AutoCompleteRenderer.java:105)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:924)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:559)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1689)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:399)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:319)
at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60)
at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:417)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Jul 28, 2015 5:13:50 PM org.apache.catalina.core.StandardWrapperValve invoke
SCHWERWIEGEND: Servlet.service() for servlet [Faces Servlet] in context with path [/AutocompleteObject] threw exception
java.lang.IllegalStateException: CDATA tags may not nest
at com.sun.faces.renderkit.html_basic.HtmlResponseWriter.startCDATA(HtmlResponseWriter.java:681)
at javax.faces.context.ResponseWriterWrapper.startCDATA(ResponseWriterWrapper.java:179)
at javax.faces.context.PartialResponseWriter.startError(PartialResponseWriter.java:341)
at org.primefaces.context.PrimePartialResponseWriter.startError(PrimePartialResponseWriter.java:174)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:200)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:124)
at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Your converter is bound to an EL expression. Change the part with the converter to: converter="TextConverter" and it will work.
NOTE:
If your Converter isn't annotated with #FacesConverter, then you have to use the EL-expression: converter="#{textConverter}" in your facelet!
If you run into troubles by using any PrimeFaces component you should always refer to the PrimeFaces-ShowCase. Most of the time the mistake is trivial.
SOLVED : Go through comments/chat
I am using Spring 4.1.1 with annotation based configuration. While trying to use eclipselink with spring, i get error on merge method stating No transaction is currently active
Following is the stacktrace:
javax.persistence.TransactionRequiredException:
Exception Description: No transaction is currently active
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.throwCheckTransactionFailedException(EntityTransactionWrapper.java:87)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.checkForTransaction(EntityTransactionWrapper.java:50)
Exception occured at : javax.persistence.TransactionRequiredException:
Exception Description: No transaction is currently active
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:2041)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:863)
at com.cdl.box.dao.GenericDao.merge(GenericDao.java:61)
at com.cdl.box.dao.GenericDao$$FastClassBySpringCGLIB$$9e11ea6a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.cdl.box.dao.PersonDao$$EnhancerBySpringCGLIB$$51ee0a8f.merge(<generated>)
at com.cdl.box.service.person.PersonService.addPerson(PersonService.java:23)
at com.cdl.box.service.person.PersonService$$FastClassBySpringCGLIB$$dbc06f33.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.cdl.box.service.person.PersonService$$EnhancerBySpringCGLIB$$35eaf713.addPerson(<generated>)
at com.cdl.box.controller.PersonController.add(PersonController.java:55)
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.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
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:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
WebConfig.java
#EnableWebMvc
#Configuration
#ComponentScan("com.myapp")
#PropertySource(value = "classpath:application.properties")
#EnableTransactionManagement(proxyTargetClass=true)
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
System.out.println("UrlBasedViewResolver........");
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Bean
MultipartResolver multipartResolver() {
MultipartResolver resolver = new StandardServletMultipartResolver();
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("In Resouce Handler");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/defaultTheme/");
}
}
DBConfig.java
import java.util.Properties;
import javax.sql.DataSource;
import org.eclipse.persistence.platform.database.DatabasePlatform;
import org.eclipse.persistence.platform.database.MySQLPlatform;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.instrument.classloading.SimpleLoadTimeWeaver;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.jolbox.bonecp.BoneCPDataSource;
#Configuration
#EnableTransactionManagement(proxyTargetClass = true)
#EnableLoadTimeWeaving
public class DBConfig {
#Value("${jdbc.driverClassName}")
private String driverClassName;
#Value("${jdbc.url}")
private String url;
#Value("${jdbc.username}")
private String username;
#Value("${jdbc.password}")
private String password;
#Value("${eclipselink.persistenceUnitName}")
private String persistenceUnitName;
#Bean()
public DataSource getDataSource() {
BoneCPDataSource ds = new BoneCPDataSource();
System.out.println("Driver Name : " + driverClassName);
System.out.println("Url : " + url);
ds.setDriverClass(driverClassName);
ds.setJdbcUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setMaxConnectionsPerPartition(5);
ds.setMinConnectionsPerPartition(2);
ds.setAcquireIncrement(2);
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(getDataSource());
em.setJpaDialect(jpaDialect());
em.setPackagesToScan("com.myapp.model", "com.myapp.model.person");
em.setPersistenceUnitName(persistenceUnitName);
DatabasePlatform dp = new MySQLPlatform();
em.setJpaVendorAdapter(getEclipseLinkJpaVendorAdapter());
//em.setLoadTimeWeaver(new SimpleLoadTimeWeaver());
em.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return em;
}
#Bean
public EclipseLinkJpaVendorAdapter getEclipseLinkJpaVendorAdapter() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.eclipse.persistence.platform.database.MySQLPlatform");
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public JpaDialect jpaDialect() {
return new EclipseLinkJpaDialect();
}
}
WebInitializer.java
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebInitializer implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
// TODO Auto-generated method stub
System.out.println("In WebApplicationInitializer.....");
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));
servletContext.setInitParameter("contextConfigLocation", "<NONE>");
rootContext.register(DBConfig.class);
rootContext.register(WebConfig.class);
rootContext.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
servlet.setMultipartConfig(new MultipartConfigElement("/img", 1024*1024*5, 1024*1024*5*5, 1024*1024));
}
}
Fetching the data works perfectly. Error occurs during insert/update using eclipselink.
I went through lot of posts & applied all suggestions. But unfortunately it is not working. I am not sure what I am missing. Do you see anything wrong with the configuration ? Please suggest me what I am doing wrong here.
EDIT:
Following is my service class with #Transactional.
import java.util.List;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.myapp.dao.PersonDao;
import com.myapp.model.person.Person;
#Service
#Transactional(propagation=Propagation.REQUIRED)
public class PersonService {
#Autowired
private PersonDao personDao;
public void addPerson(Person person) {
Person p = personDao.merge(person);
System.out.println(p.getCity());
}
public void updatePerson(Person person) {
personDao.persist(person);
}
public Person getPerson(int id) {
return personDao.findById(id);
}
public void deletePerson(int id) {
personDao.deleteById(id);
}
public List<Person> getPersons(int first, int rows){
ReadAllQuery readAllQuery = new ReadAllQuery(Person.class);
readAllQuery.setJPQLString("SELECT OBJECT(per) FROM Person per");
return personDao.executeReadAllQuery(readAllQuery, first, rows);
}
}
With #Transactional on service class I get following error while I start Tomcat
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personController' defined in file [D:\Hemraj-Dev\apache-tomcat-7.0.56\webapps\yourbox\WEB-INF\classes\com\myapp\controller\PersonController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.myapp.service.person.PersonService]: : Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:751)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1036)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
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:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1081)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1006)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:743)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 36 more
Caused by: java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:741)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:551)
... 38 more
EDIT2:
I have replaced new stacktarce on top of question for No Transaction is currently active error. Following is my DAOs.
PersonDao.java:
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.myapp.model.person.Person;
#Repository("personDao")
public class PersonDao extends GenericDao<Person, Integer> {
#Override
public int deleteById(Integer id) {
Query q = getEntityManager().createQuery(
"delete from Employees where employeeId = :id");
q.setParameter("id", id);
return q.executeUpdate();
}
}
GenericDao.java
public class GenericDao<E, ID extends Serializable>{
private final Class<E> persistentClass;
protected EntityManager entityManager;
private EntityManagerFactory emf;
#PersistenceContext(unitName = "cdlbox")
private EntityManager em;
#Value("${eclipselink.persistenceUnitName}")
private String persistenceUnitName;
#SuppressWarnings("unchecked")
public GenericDao() {
this.persistentClass = (Class<E>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
protected Class<E> getEntityClass() {
return persistentClass;
}
protected EntityManager getEntityManager(){
return em;
}
public E merge(E entity) {
E e = null;
try{
e = em.merge(entity);
em.flush();
}catch (Exception ex) {
System.out.println("Exception occured at : " + ex);
ex.printStackTrace();
}
return e;
}
public void persist(E entity) {
em.persist(entity);
}
public void remove(E entity) {
em.remove(entity);
}
public E findById(ID id) {
return em.find(getEntityClass(), id);
}
#SuppressWarnings("unchecked")
public List<E> executeNamedQuery(String queryName,
Map<String, Object> parameterMap) {
Query query = em.createNamedQuery(
queryName);
if (parameterMap != null) {
for (String param : parameterMap.keySet()) {
query.setParameter(param, parameterMap.get(param));
}
}
return query.getResultList();
}
public List<E> executeNamedQuery(String queryName) {
return executeNamedQuery(queryName, null);
}
#SuppressWarnings("unchecked")
public int getCount(String countField, Expression expr) {
ReportQuery query = new ReportQuery(getEntityClass(), null);
query.setSelectionCriteria(expr);
query.addCount("count", query.getExpressionBuilder().get(countField)
.distinct());
List<ReportQueryResult> result = (List<ReportQueryResult>) getSession().executeQuery(query);
ReportQueryResult reportQueryResult = result.get(0);
BigDecimal count = (BigDecimal) reportQueryResult.getResults().get(0);
return count.intValueExact();
}
protected Session getSession() {
//EntityManagerImpl has to be imported as org.eclipse.persistence.internal.jpa.EntityManagerImpl
Session session = ((EntityManagerImpl) em).getActiveSession();
return session;
}
public List<E> executeReadAllQuery(ReadAllQuery readAllQuery, int first,
int rows) {
readAllQuery.setFirstResult(first);
readAllQuery.setMaxRows(first + rows);
return executeDatabaseQuery(readAllQuery);
}
#SuppressWarnings("unchecked")
public List<E> executeDatabaseQuery(DatabaseQuery q) {
List<E> resultList = (List<E>) getSession().executeQuery(q);
return resultList;
}
public int deleteById(ID id) {
// TODO Auto-generated method stub
return 0;
}
}
EDIT3:
Got this exception while using #PersistenceContext
If you are using EclipseLink and JOTM running on Tomcat then in the persistence.xml, I guess you forgot the property:
<properties>
<property name="eclipselink.target-server" value="org.eclipse.persistence.transaction.jotm.JotmTransactionController"/>
</properties>