BeginnerQuestion Spring and MongoDB findAll - spring

I'm a Beginner with Spring and MongoDB and just tried to write a Class "Person" which has firstName and LastName and ID.
#Document(collection = "persons")
public class Person {
#org.springframework.data.annotation.Id
private String Id;
private String firstName;
private String lastName;
private int age = 0;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
And I connect to a MongoDB with this Interface:
public interface PersonRepository extends MongoRepository<Person, String> {
And the Personcontroller should return all Persons which are in the database collection named "persons":
#RestController
public class PersonController {
private PersonRepository repo;
#GetMapping("/persons")
public ResponseEntity getAllPersons(){
return ResponseEntity.ok(repo.findAll());
}
}
So in my Mongo Database are 2 Persons:
_id:5ed7b666eabc4b2a9474fd61
firstName:"Rick"
lastName:"Sanchez"
age:0
_class:"com.petziferum.backend.model.Person"
_id:5ed7b666eabc4b2a9474fd62
firstName:"Morty"
lastName:"Smith"
age:0
_class:"com.petziferum.backend.model.Person"
But if I send a Get Request to localhost:8000/persons, I get an Error 500 and can't find my Mistake.
Can someone help me please? Cant even find any easy Documentations without search functions and all that.
I just want an Array list or Object List in return when requesting /persons
Stacktrace:
"trace": "java.lang.NullPointerException\r\n
\tat com.petziferum.backend.controller.PersonController.getAllPersons(PersonController.java:24)\r\n
\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n
\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n
\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n
\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n
\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\r\n
\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\r\n
\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)\r\n
\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)\r\n
\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\r\n
\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n
\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\r\n
\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n
\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n
\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)\r\n
\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:634)\r\n
\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n
\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n
\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n
\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n
\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n
\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n
\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n
\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n
\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n
\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n
\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n
\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n
\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n
\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n
\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n
\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n
\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n
\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)\r\n
\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n
\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)\r\n
\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)\r\n
\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n
\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\r\n
\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\r\n
\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n
\tat java.lang.Thread.run(Thread.java:745)\r\n",
"message": "No message available",
"path": "/persons/"
}

Your repo is null. You need to inject your repo into your controller either by using constructor injection or #Autowired.

Related

Error Creating Application Context on Basic Spring-Boot-Data JPA Project

I am trying to create a basic Spring-Boot project that only deals with #Entity annotated classes and a basic JpaRepository for those entities.
When I try to run a basic test for the basic configuration of the project I get the following exception through JUnit(Jupiter).
java.lang.IllegalStateException:
Failed to load ApplicationContext for
[MergedContextConfiguration#717a8a76
testClass = com.example.demo.PersistenceLayerApplicationTests,
locations = [],
classes = [com.example.demo.PersistenceLayerApplication],
contextInitializerClasses = [],
activeProfiles = [],
propertySourceLocations = [],
propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true"],
contextCustomizers =
[org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer#9da1,
org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0,
org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#5fd4f8f5,
org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#2f8dad04,
org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#44821a96,
org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0,
org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#22e357dc,
org.springframework.boot.test.context.SpringBootTestAnnotation#978fd0ca],
contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:142)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:141)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:97)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:241)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:377)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:382)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:377)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:376)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:289)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:288)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:105)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:104)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1751)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1130)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:905)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:59)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:47)
at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1386)
at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:543)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:184)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:118)
... 72 more
Caused by: jakarta.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:421)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1797)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1747)
... 93 more
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:98)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:56)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:68)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.jdbcStatement(GenerationTargetToDatabase.java:77)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:53)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:419)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:403)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:272)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:178)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:149)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:117)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:242)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:143)
at java.base/java.util.HashMap.forEach(HashMap.java:1421)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:140)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:336)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:415)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1425)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:66)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:376)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
... 97 more
Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:319)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:247)
at org.postgresql.Driver.makeConnection(Driver.java:434)
at org.postgresql.Driver.connect(Driver.java:291)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:359)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:470)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:100)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:284)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:41)
... 115 more
Caused by: java.net.ConnectException: Connection refused: no further information
at java.base/sun.nio.ch.Net.pollConnect(Native Method)
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672)
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:539)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:594)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:633)
at org.postgresql.core.PGStream.createSocket(PGStream.java:241)
at org.postgresql.core.PGStream.<init>(PGStream.java:98)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:109)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:235)
... 129 more
Here is my build.gradle file
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
ext {
set('testcontainersVersion', "1.17.6")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'org.postgresql:postgresql'
runtimeOnly 'org.liquibase:liquibase-core'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
}
dependencyManagement {
imports {
mavenBom "org.testcontainers:testcontainers-bom:${testcontainersVersion}"
}
}
tasks.named('test') {
useJUnitPlatform()
}
Here is the Spring Boot Application file(PersistencLayerApplication.java)
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class PersistenceLayerApplication {
public static void main(String[] args) {
SpringApplication.run(PersistenceLayerApplication.class, args);
}
}
Here is the #Entity class
package com.example.demo.data.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
#Entity
public class PersonEntity {
#Id
#GeneratedValue
private Long id;
private String firstName;
private String lastName;
protected PersonEntity() {}
public PersonEntity(String firstName, String lastName) {
super();
this.id = null;
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here is the Repository class
package com.example.demo.data.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.data.entity.PersonEntity;
public interface PersonRepository extends JpaRepository<PersonEntity, Long> {
}
Here is my application.yaml file
#Deployment Options for Spring Data and PostgreSQL
#Not yet confirmed to be correct
spring:
jpa:
database: POSTGRESQL
show-sql: true
hibernate:
ddl-auto: create-drop
datasource:
url: "jdbc:postgresql:localhost:5432/datamodel"
username: foo
password: bar
driverClassName: org.postgresql.Driver
sql:
init:
platform: postgres
And here is my test file
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class PersistenceLayerApplicationTests {
#Test
void contextLoads() {
}
}
I have also tried to use an #DataJpaTest annotated test class thinking that I didn't configure my database properly but that one failed with the same error.
Here is that test file...
package com.example.demo.data;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.TestPropertySourceUtils;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import com.example.demo.data.PersonJpaTest.DataSourceInitializer;
import com.example.demo.data.entity.PersonEntity;
import com.example.demo.data.repo.PersonRepository;
#Testcontainers
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
#ContextConfiguration(initializers = DataSourceInitializer.class)
public class PersonJpaTest {
#Autowired private PersonRepository personRepository;
#Container //
static final PostgreSQLContainer<?> database = //
new PostgreSQLContainer<>("postgres:15.2-alpine") //
.withUsername("postgres");
public static class DataSourceInitializer //
implements ApplicationContextInitializer
<ConfigurableApplicationContext> {
#Override
public void initialize(ConfigurableApplicationContext applicationContext) {
TestPropertySourceUtils.
addInlinedPropertiesToEnvironment( applicationContext,
"spring.datasource.url=" + database.getJdbcUrl(),
"spring.datasource.usernam=" + database.getUsername(),
"spring.datasource.password=" + database.getPassword(),
"spring.jpa.hibernate.ddl-auto=create-drop");
}
}
#BeforeEach
void setUp() {
personRepository.saveAll(
List.of(
new PersonEntity(
"Mike",
"Bolger"),
new PersonEntity(
"Paul",
"Corrigan"),
new PersonEntity(
"Brenda",
"Butler"),
new PersonEntity(
"Gerald",
"Ford"),
new PersonEntity(
"Joe",
"Craig")
));
}
#Test
void findAll() {
List<PersonEntity> allPersons = personRepository.findAll();
for(PersonEntity person : allPersons) {
System.out.println(person.getFirstName() + " " + person.getLastName());
}
}
}
I know that there is a problem with the auto-generated ApplicationContext but I cannot see what I have done wrong. The book that I copied the example code from is essentially the same.
I tried running the test through the H2 database and got the same error.
Here is the application.yaml I used for that test
spring:
datasource:
url: jdbc:h2:mem:mydb
username: sa
password: password
driverClassName: org.h2.Driver
jpa:
spring.jpa.database-platform: org.hibernate.dialect.H2Dialect
And here is the build.gradle for the test.
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
ext {
set('testcontainersVersion', "1.17.6")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
//runtimeOnly 'org.postgresql:postgresql'
//runtimeOnly 'org.liquibase:liquibase-core'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.testcontainers:junit-jupiter'
//testImplementation 'org.testcontainers:postgresql'
}
dependencyManagement {
imports {
mavenBom "org.testcontainers:testcontainers-bom:${testcontainersVersion}"
}
}
tasks.named('test') {
useJUnitPlatform()
}

JPA No property findAll found for type Product

My repository:
#Repository
public interface ProductDao extends JpaRepository<Product,Long>,JpaSpecificationExecutor<Product> {
Page<Product> findAll(Specification<Product> specification,Pageable pageable);
}
My service:
...
#Autowired
public ProductServiceImpl(ProductRepository repository, ProductDao productDao, ProductImgService productImgService, ProductClassService productClassService, AuthUserService authUserService, DeviceService deviceService){
super(repository);
this.productDao = productDao;
this.productImgService = productImgService;
this.productClassService = productClassService;
this.authUserService = authUserService;
this.deviceService = deviceService;
}
final
ProductDao productDao;
...
I use it in the service like this:
midResult = productDao.findAll((root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> list = new ArrayList<>();
list.add(criteriaBuilder.equal(root.get("ouId").as(Long.class),product.getOuId()));
if(product.getPclassId()!=null)
list.add(criteriaBuilder.equal(root.get("pclassId").as(Long.class),product.getPclassId()));
if(product.getProductStatus()!=null)
list.add(criteriaBuilder.equal(root.get("productStatus").as(Integer.class),product.getProductStatus()));
if(product.getProductName()!=null)
list.add(criteriaBuilder.equal(root.get("productName").as(String.class),product.getProductName()));
if(product.getCreator()!=null)
list.add(criteriaBuilder.equal(root.get("creator").as(Integer.class),product.getCreator()));
list.add(criteriaBuilder.between(root.get("createTimeTmp").as(Long.class),Long.parseLong(finalStarttsp),Long.parseLong(finalEndtsp)));
Predicate[] p = new Predicate[list.size()];
criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
return criteriaQuery.getRestriction();
}, pageable);
The Product Class definition is good .
And when I run this code , error turned out to be :
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findAll found for type Product!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:247) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:398) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:378) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:86) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.mybatis.repository.query.PartTreeMybatisQuery.<init>(PartTreeMybatisQuery.java:81) ~[spring-data-mybatis-1.0.17.RELEASE.jar:na]
at org.springframework.data.mybatis.repository.query.MybatisQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(MybatisQueryLookupStrategy.java:71) ~[spring-data-mybatis-1.0.17.RELEASE.jar:na]
at org.springframework.data.mybatis.repository.query.MybatisQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(MybatisQueryLookupStrategy.java:120) ~[spring-data-mybatis-1.0.17.RELEASE.jar:na]
at org.springframework.data.mybatis.repository.query.MybatisQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(MybatisQueryLookupStrategy.java:50) ~[spring-data-mybatis-1.0.17.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
at org.springframework.data.mybatis.repository.support.MybatisRepositoryFactoryBean.afterPropertiesSet(MybatisRepositoryFactoryBean.java:64) ~[spring-data-mybatis-1.0.17.RELEASE.jar:na]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
I'm using springboot and there's no config like #EnableJpaRepositories
But it don't seems to be necessary cause other repository is good .
You are using spring-data in incorrect way. When you write method findAll in repository, it will look for given attribute in entity.
For example, you have an entity User with attribute firstName. Then you can defined method like, findByFirstName.
In given example, spring-data looking for attribute all which is not available as a part of Product.
In this case, you need to write your own query using #Query annotation.
BTW, what you want to achieve?
It works like this for me:
#NonNull
Page<Product> findAll(#Nullable Specification<Product> specification, #NonNull Pageable pageable);

LazyInitializationException with SpringOpenEntityManagerInViewFilter

Despite I'm using SpringOpenEntityManagerInViewFilter, I'm getting LazyInitializationException after to get some results.
The mystery is why I'm getting the first results (rows) right and then it gets tired and I don't get more results.
I've try everything I've read here I've almost read all the post here, I'm still stuck here.
I'm newbie with Spring data jpa, I suspect it could be a nonsense
these are my files:
web.xml
.....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/*.xml</param-value>
</context-param>
<filter>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
ApplicationContext.xml
<context:annotation-config />
<jpa:repositories base-package="com.previsionx.web.repositories" />
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="com.previsionx.web"> </context:component-scan>
<!-- Necessary to get the entity manager injected into the factory bean -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- Define Hibernate JPA Vendor Adapter -->
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform"
value="org.hibernate.dialect.MySQLDialect" />
</bean>
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="previsionx"></property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Detect #Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
PoSrvc.java
#Transactional
public class PoSrvc implements IPoSrvc {
#Autowired
private IPoRepository poRepository;
#Autowired
private IPoBuRepository poBuRepository;
#Override
#Transactional
public List<Po> getAllByBu(long buId) {
Set<Po> poSet = new LinkedHashSet<Po>();
poSet.addAll(poBuRepository.findPoByBuId(buId));
poSet.addAll(poRepository.findByCreatorBuId(buId));
List<Po> list = new LinkedList<Po>();
list.addAll(poSet);
return list;
}
IPoRepository.java
public interface IPoRepository extends JpaRepository<Po,Long>{
List<Po> findByCreatorBuId(long buId);
Po findById(long id);
IPoBuRepository.java
public interface IPoBuRepository extends JpaRepository<PoBu, Long> {
#Query("SELECT p FROM PoBu pb INNER JOIN pb.po p WHERE pb.po.id = p.id AND pb.bu.id=:id ORDER BY pb.po.ref")
List<Po> findPoByBuId(#Param("id") long id);
ManagePo.java
#ManagedBean
#ViewScoped
public class ManagePO implements Serializable {
......
#ManagedProperty("#{poSrvc}")
#Autowired
private IPoSrvc poSrvc;
#ManagedProperty("#{buSrvc}")
#Autowired
private IBuSrvc buSrvc;
#PostConstruct
public void init(){
this.readOnly=false;
poList = poSrvc.getAllByBu(appcontext.getBuId());
........
}
Any suggestion is welcome because I don't know whatelse to do :(
Thank you very much in advance
EDIT:
the exception trace
GRAVE: Error Rendering View[/secure/managepo.xhtml]
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.previsionx.entities.Po.PoBuList, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:572)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:212)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:153)
at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:278)
at javax.faces.model.ListDataModel.isRowAvailable(ListDataModel.java:109)
at javax.faces.model.ListDataModel.setRowIndex(ListDataModel.java:184)
at javax.faces.model.ListDataModel.setWrappedData(ListDataModel.java:219)
at javax.faces.model.ListDataModel.<init>(ListDataModel.java:78)
at com.sun.faces.facelets.component.UIRepeat.getDataModel(UIRepeat.java:263)
at com.sun.faces.facelets.component.UIRepeat.setIndex(UIRepeat.java:523)
at com.sun.faces.facelets.component.UIRepeat.process(UIRepeat.java:577)
at com.sun.faces.facelets.component.UIRepeat.encodeChildren(UIRepeat.java:1110)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at org.primefaces.component.column.Column.renderChildren(Column.java:304)
at org.primefaces.component.datatable.DataTableRenderer.encodeCell(DataTableRenderer.java:963)
at org.primefaces.component.datatable.DataTableRenderer.encodeRow(DataTableRenderer.java:919)
at org.primefaces.component.datatable.DataTableRenderer.encodeRows(DataTableRenderer.java:830)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:777)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:740)
at org.primefaces.component.datatable.feature.PageFeature.encode(PageFeature.java:36)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:78)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:582)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at org.primefaces.component.api.UIData.visitTree(UIData.java:692)
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 javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:322)
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:430)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
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 com.previsionx.web.utils.NoCacheFilter.doFilter(NoCacheFilter.java:33)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
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:312)
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've solved using a Primefaces Lazy datatable
The problem seems to be that once the page is rendered the hibernate session gets closed.
Service, repository and manageBean have chaged a bit
Service:
#Component
public class PoSrvc implements IPoSrvc {
#Autowired
private IPoBuRepository poBuRepository;
#Override
#Transactional
public List<Po> getAllByBu(long buId, int page, int results, String sort, SortOrder sortOrder) {
Pageable pageable = new PageRequest(
page, results,new Sort(new Order(SortOrder.ASCENDING.equals(sortOrder)? Direction.ASC: Direction.DESC, "po."+sort))
);
return poBuRepository.findPoByBuId(buId,pageable);
}
#Override
public int getCountAllByBu(long buId) {
return poBuRepository.findCountAllByBuId(buId);
}
Repository:
public interface IPoBuRepository extends JpaRepository<PoBu, Long> {
#Query("SELECT DISTINCT po FROM PoBu pb WHERE (pb.bu.id=:id OR pb.po.creatorBu.id=:id) AND pb.po.deleted=false")
List<Po> findPoByBuId(#Param("id") long id,Pageable pageable);
#Query("SELECT COUNT (DISTINCT pb.po) FROM PoBu pb WHERE (pb.bu.id=:id OR pb.po.creatorBu.id=:id) AND pb.po.deleted=false")
int findCountAllByBuId(#Param("id") long id);
And my managedBean:
#ManagedBean
#ViewScoped
public class ManagePO implements Serializable {
private static final long serialVersionUID = 8947292155668339391L;
#ManagedProperty(value="#{appContext}")
private AppContext appcontext;
#ManagedProperty("#{poSrvc}")
private IPoSrvc poSrvc;
private LazyDataModel<Po> lazyModel;
#PostConstruct
public void init(){
this.readOnly=false;
this.lazyModel = new LazyPoDataModel(appcontext.getBuId(), poSrvc);
Finally this the Lazy table model:
public class LazyPoDataModel extends LazyDataModel<Po> {
private static final long serialVersionUID = 1L;
private long buId;
private IPoSrvc poSrvc;
public LazyPoDataModel(long buId, IPoSrvc poSrvc) {
super();
this.buId = buId;
this.poSrvc = poSrvc;
this.setRowCount(this.poSrvc.getCountAllByBu(buId));
}
#Override
public List<Po> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
List<Po> data = new LinkedList<Po>();
int page = first/pageSize;
if(sortField==null){
sortField = "ref";
}
data=poSrvc.getAllByBu(buId, page, pageSize, sortField, sortOrder);
return data;
}
Now no LazyInitializationException is thrown anymore!!!
Thanks for clues!
EDIT:
the XHTML:
<p:dataTable id="po_tbl" value="#{managePO.lazyModel}" styleClass="order-table" headerClass="order-table-header" rowClasses="order-table-odd-row,order-table-even-row" var="po" style="width:1000px;"
resizableColumns="true" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,20,30,50" rows="10" lazy="true">
<p:column sortBy="#{po.ref}">
<!-- column header -->
<f:facet name="header">#{msg['tbl_hdr_po.manage_po']}</f:facet>
<!-- row record -->
<h:outputText value="#{po.ref}" />
</p:column>
<p:column styleClass="text-right">
<f:facet name="header">#{msg['tbl_hdr_total.manage_po']}</f:facet>
<h:outputText value="#{po.weight} #{po.weightUnit}" />
</p:column>
<p:column sortBy="#{po.product}">
<f:facet name="header">#{msg['tbl_hdr_product.manage_po']}</f:facet>
#{po.product}
</p:column>
<p:column sortBy="#{po.creatorBu.ref}">
<f:facet name="header">#{msg['tbl_hdr_creator.manage_po']}</f:facet>
#{po.creatorBu.ref}
</p:column>

java.lang.reflect.InvocationTargetException in sample Struts2 spring4.1 jpa/hibernate3.1.6

I'm trying to develop a basic application with didactic purposes, using Struts 2 + Spring 4.1 + JPA / Hibernate 3.6 with Netbeans 8 as IDE. I managed to create and update users without problem but when I try to login I get java.lang.reflect.InvocationTargetException, specifically in this instruction:
Query query = entityManager.createQuery(
"from User where username = :username")
.setParameter("username", username);
the database is created and contains a couple of records in each table.
I will appreciate greatly any help on why this is happening to me.
Here is a list of the libraries that I'm using:
Struts2 2.3.16 - asm-3.3.jar
Struts2 2.3.16 - asm-commons-3.3.jar
Struts2 2.3.16 - asm-tree-3.3.jar
Struts2 2.3.16 - commons-fileupload-1.3.1.jar
Struts2 2.3.16 - commons-io-2.2.jar
Struts2 2.3.16 - commons-lang3-3.1.jar
Struts2 2.3.16 - freemarker-2.3.19.jar
Struts2 2.3.16 - javassist-3.11.0.GA.jar
Struts2 2.3.16 - ognl-3.0.6.jar
Struts2 2.3.16 - struts2-core-2.3.16.3.jar
Struts2 2.3.16 - xwork-core-2.3.16.3.jar
Struts2 2.3.16 - antlr-2.7.2.jar
Struts2 2.3.16 - commons-collections-3.1.jar
Struts2 2.3.16 - commons-logging-1.1.3.jar
Struts2 2.3.16 - commons-logging-api.1.1.jar
Struts2 2.3.16 - json-lib-2.3-jdk15.jar
Struts2 2.3.16 - aopalliance-1.0.jar
Struts2 2.3.16 - struts2-spring-plugin-2.3.16.3.jar
Spring 4.1 - spring-aop-4.1.0.RELEASE.jar
Spring 4.1 - spring-aspects-4.1.0.RELEASE.jar
Spring 4.1 - spring-beans-4.1.0.RELEASE.jar
Spring 4.1 - spring-context-4.1.0.RELEASE.jar
Spring 4.1 - spring-context-support-4.1.0.RELEASE.jar
Spring 4.1 - spring-core-4.1.0.RELEASE.jar
Spring 4.1 - spring-expression-4.1.0.RELEASE.jar
Spring 4.1 - spring-instrument-4.1.0.RELEASE.jar
Spring 4.1 - spring-instrument-tomcat-4.1.0.RELEASE.jar
Spring 4.1 - spring-jdbc-4.1.0.RELEASE.jar
Spring 4.1 - spring-jms-4.1.0.RELEASE.jar
Spring 4.1 - spring-messaging-4.1.0.RELEASE.jar
Spring 4.1 - spring-orm-4.1.0.RELEASE.jar
Spring 4.1 - spring-oxm-4.1.0.RELEASE.jar
Spring 4.1 - spring-test-4.1.0.RELEASE.jar
Spring 4.1 - spring-tx-4.1.0.RELEASE.jar
Spring 4.1 - spring-web-4.1.0.RELEASE.jar
Spring 4.1 - spring-webmvc-4.1.0.RELEASE.jar
Spring 4.1 - spring-webmvc-portlet-4.1.0.RELEASE.jar
Spring 4.1 - spring-websocket-4.1.0.RELEASE.jar
Spring 4.1 - org-apache-commons-logging.jar
Spring 4.1 - cglib-2.2.jar
MySQL JDBC Driver- mysql-connector-java-5.1.23-bin.jar
Hibernate 4.3.6 - antlr-2.7.7.jar
Hibernate 4.3.6 - dom4j-1.6.1.jar
Hibernate 4.3.6 - hibernate-core-4.3.6.Final.jar
Hibernate 4.3.6 - hibernate-jpa-2.1-api-1.0.0.Final.jar
Hibernate 4.3.6 - jandex-1.1.0.Final.jar
Hibernate 4.3.6 - javassist-3.18.1-GA.jar
Hibernate 4.3.6 - jboss-logging-3.1.3.GA.jar
Hibernate 4.3.6 - jboss-logging-annotations-1.2.0.Beta1.jar
Hibernate 4.3.6 - jboss-transaction-ap_1.2_spec-1.0.0.Final.jar
Hibernate 4.3.6 - hibernate-entitymanager-4.3.6.Final.jar
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="portfolioService" class="portfolio.utils.PortfolioServiceJPAImpl"></bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/portfolio" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
struts.xml
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="Login" class="portfolio.Login">
<result type="redirectAction">
<param name="actionName">AdminPortfolio</param>
</result>
<result name="input">index.jsp</result>
</action>
<action name="AdminPortfolio">
<result>admin.jsp</result>
</action>
</package>
</struts>
Login.java
package portfolio;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import portfolio.utils.PortfolioServiceInterface;
import portfolio.utils.User;
public class Login extends ActionSupport {
public Login() {
}
#Override
public String execute() throws Exception {
User user = getPortfolioService().authenticateUser(getUsername(), getPassword());
if (user == null) {
/* User not valid, return to input page. */
return INPUT;
} else {
session.put("user", user);
}
return SUCCESS;
}
private String username;
private String password;
private Map session;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public void validate() {
/* Check that fields are not empty */
if (getPassword().length() == 0) {
addFieldError("password", getText("password.required"));
}
if (getUsername().length() == 0) {
addFieldError("username", getText("username.required"));
}
}
/*
* Field with getter and setter for PortfolioService object, which will be injected
* via Spring.
*/
PortfolioServiceInterface portfolioService;
public PortfolioServiceInterface getPortfolioService() {
return portfolioService;
}
public void setPortfolioService(PortfolioServiceInterface portfolioService) {
this.portfolioService = portfolioService;
}
public void setSession(Map session) {
this.session = session;
}
}
User.java
package portfolio.utils;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class User {
private String username;
private String password;
private String firstName;
private String lastName;
private String email;
#OneToMany(cascade = {CascadeType.ALL}, mappedBy = "owner")
private Set<Portfolio> portfolios = new HashSet<Portfolio>();
#Id
#GeneratedValue
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set getPortfolios() {
return portfolios;
}
public void setPortfolios(Set portfolios) {
this.portfolios = portfolios;
}
public void addPortfolio(Portfolio portfolio) {
portfolio.setOwner(this);
portfolios.add(portfolio);
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Portfolio.java
package portfolio.utils;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
#Entity
public class Portfolio {
private String name;
#ManyToOne(targetEntity = portfolio.utils.User.class, optional = false)
private User owner;
#Id
#GeneratedValue
private Long id;
#ElementCollection
#JoinTable(name = "portfolio_image", joinColumns = #JoinColumn(name = "portfolio_id"))
private Set<String> pics = new HashSet<String>();
public Set getPics() {
return pics;
}
public void setPics(Set pics) {
this.pics = pics;
}
public void addPic(String pic) {
pics.add(pic);
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PortfolioServiceJPAImpl.java
package portfolio.utils;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
public class PortfolioServiceJPAImpl implements PortfolioServiceInterface {
private EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
public User authenticateUser(String username, String password) {
System.out.println("Authenticating: username = " + username);
User validUser = null;
Query query = entityManager.createQuery("from User where username = :username").setParameter("username", username);
List result = query.getResultList();
if (!result.isEmpty()) {
User user = (User) result.get(0);
/* If the username mapped to a real user, check password */
if (user != null && user.getPassword().equals(password)) {
validUser = user;
}
}
return validUser;
}
}
Persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="punit">
<properties>
<property name="hibernate.hbm2ddl.auto" value="none"/>
</properties>
</persistence-unit>
</persistence>
Exception:
SEVERE [http-nio-8084-exec-6] org.apache.struts2.dispatcher.Dispatcher.error Exception occurred during processing request: null
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I
at org.hibernate.hql.internal.ast.HqlSqlWalker.generateNamedParameter(HqlSqlWalker.java:1023)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.parameter(HqlSqlBaseWalker.java:3396)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1351)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4686)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4159)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2104)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:796)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:597)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:342)
at com.sun.proxy.$Proxy23.createQuery(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:289)
at com.sun.proxy.$Proxy23.createQuery(Unknown Source)
at portfolio.utils.PortfolioServiceJPAImpl.authenticateUser(PortfolioServiceJPAImpl.java:22)
at portfolio.Login.execute(Login.java:16)
... 77 more
solved
Thanks to Andrea Ligios comment I understood better what was the real exception and was already settled in another question. Sorry I doubled the question.
I had two versions of the library "antlr" simply remove the struts antlr lib and use only antlr of hibernate.
Thanks to all users for their comments.

NPE when invoking getter of managed property

I am learning Spring with Hibernate and am creating a movie rental application using JSF as front end framework.
I have an application scoped managed property in my registration bean which is view scoped. In the register() method to insert the user details in the database, I invoke the service locator implementation bean to get a reference to the required service implementation. However, I get an NPE when I invoke the getter of the service locator property.
Following are my managed beans...
Registration Bean
#ManagedBean
#ViewScoped
public class RegistrationBean extends BaseBean implements Serializable
{
private static final long serialVersionUID = -6449858513581500971L;
private String userID;
private String password;
private String firstName;
private String lastName;
private String email;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String pincode;
public RegistrationBean() {
super();
}
// getter / setters...
public String register()
{
String nextPage = null;
try {
RegistrationDetails userDetails = ModelBuilder.populateRegistrationData(this);
// NPE at this line. getServiceLocator() returns null
int registrationID = getServiceLocator().getUserService().registerUser(userDetails);
nextPage = "success";
}
catch (RegistrationException e) {
LOGGER.error(e.getMessage());
}
return nextPage;
}
}
Base Bean
public class BaseBean
{
#ManagedProperty("#{serviceLocator}")
protected IServiceLocator serviceLocator;
protected IServiceLocator getServiceLocator() {
return serviceLocator;
}
public void setServiceLocator(IServiceLocator serviceLocator) {
this.serviceLocator = serviceLocator;
}
}
Service Locator Bean
#ManagedBean
#ApplicationScoped
public class ServiceLocator implements IServiceLocator
{
private static final String USER_SERVICE = "userService";
public ServiceLocator() {
super();
final ServletContext sc = FacesUtils.getServletContext();
this.webAppContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
this.userService = (IUserService) webAppContext.getBean(USER_SERVICE);
}
private ApplicationContext webAppContext;
private IUserService userService;
#Override
public IUserService getUserService() {
return userService;
}
public ApplicationContext getWebAppContext() {
return webAppContext;
}
}
And here is the stacktrace as seen in my Eclipse console
Oct 14, 2012 10:28:39 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{registrationBean.register}: java.lang.NullPointerException
javax.faces.FacesException: #{registrationBean.register}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 23 more
Caused by: java.lang.NullPointerException
at com.clixflix.managedbeans.RegistrationBean.register(RegistrationBean.java:118)
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.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 24 more
I am using
JSF 2.1 (Mojarra)
Hibernate 4.1
Spring 3.2
Tomcat 7
Eclipse 3.7
Could someone please point out if I have missed something??
UPDATE: Spring 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userDAO" class="com.clixflix.dao.impl.UserDAOImpl">
<constructor-arg index="0" ref="hibernateTemplate" />
</bean>
<bean id="userService" class="com.clixflix.services.impl.UserService">
<constructor-arg index="0" ref="userDAO" />
</bean>
</beans>
This post helped me to make the code work : http://www.javacodegeeks.com/2012/04/jsf-2-primefaces-3-spring-3-hibernate-4.html
However, the code does not work if I keep the Registration Bean as view scoped. Can anyone please help me figure out the reason for the same?
UPDATE: Found the solution for the ViewScope issue : http://blog.harezmi.com.tr/spring-view-scope-for-jsf-2-users/

Resources