Hibernate+Spring Boot
i can not get object
My controller
#RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public #ResponseBody
SuperStudentEntity getById(#PathVariable("id") int id) {
return new StudentDAOImpl().getById(id);
}
DAO function
public SuperStudentEntity getById(int id){
openTransactionSession();
Session s = getSession();
String sql = "SELECT * FROM student WHERE id_student =:id";
org.hibernate.query.Query query = s.createNativeQuery(sql).addEntity(SuperStudentEntity.class);
query.setParameter("id",id);
SuperStudentEntity student = (SuperStudentEntity) query.getSingleResult();
closeTransactionSesstion();
return student;
}
And get exceptions
java.lang.ClassCastException: org.codexample.ent.SuperStudentEntity cannot be cast to org.codexample.ent.SuperStudentEntity
at org.codexample.impldao.StudentDAOImpl.getById(StudentDAOImpl.java:45) ~[classes/:na]
at org.codexample.controllers.StudentController.getById(StudentController.java:54) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_101]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_101]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_101]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_101]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at ....
And browser tell me :
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu May 18 20:02:30 MSK 2017 There was an unexpected error (type=Internal Server Error, status=500). org.codexample.ent.SuperStudentEntity cannot be cast to org.codexample.ent.SuperStudentEntity
I don't understand how resolve it problem.
Related
I try to write tests with EasyMock and because I want to mock a static method I want to use PowerMock. When I want to run the test I get a ClassNotFoundException.
This is the test I wrote:
#Test
public void whenCreate_ThenCurrentAccountShouldBeFound() throws Exception {
Account oldAccount = new Account();
oldAccount.setUsername("Test");
oldAccount.setFirstName("FirstName");
oldAccount.setLastName("LastName");
oldAccount.setPassword("Password");
oldAccount.setEmail("maxmusteg#hs-pforzheim.de");
PowerMock.mockStatic(AuthenticationService.class);
PowerMock.expectNew(de.hspf.nxtgenmondial.backend.service.AuthenticationService.getCurrentlyLoggedInUser()).andReturn(oldAccount);
replayAll();
assertEquals("Username name should be Test", "Test", accountService.getCurrentAccount().getUsername());
}
This is the static method:
public static String getCurrentlyLoggedInUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof ExtendedUserDetails)
return ((ExtendedUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
else
return ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
} else
throw new IllegalStateException("No user logged in");
}
And then there is the getCurrentAccount method:
public Account getCurrentAccount() {
Optional<Account> optionalAccount = accountRepository.findOneByEmail(AuthenticationService.getCurrentlyLoggedInUser());
if (optionalAccount.isPresent())
return optionalAccount.get();
else {
log.warn("Logged in account not found in database");
return null;
}
}
This is the error message that appears. Line 105 is where PowerMock.mockStatic() is called:
org/easymock/internal/MocksControl$MockType
java.lang.NoClassDefFoundError: org/easymock/internal/MocksControl$MockType
at org.powermock.api.easymock.internal.mockstrategy.impl.DefaultMockStrategy.<init>(DefaultMockStrategy.java:8)
at org.powermock.api.easymock.PowerMock.mockStatic(PowerMock.java:287)
at de.hspf.nxtgenmondial.backend.api.account.service.AccountServiceTest.whenCreate_ThenCurrentAccountShouldBeFound(AccountServiceTest.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: org.easymock.internal.MocksControl$MockType
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:178)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 56 more
You are using a version of PowerMock that isn't compatible with your version of EasyMock. From what I see, it is PowerMock that is too old.
I've a Spring MVC application with #Controller, #Service and #Repository components (all generated from Spring Roo). I'm trying to catch a ConstraintViolationException in controller but I'm not able to. I'm trying to handle all exceptions at the controller level but the problem is when I make a call to repository from my service and if an exception occurs, I'm not getting the flow inside my catch block in the controller. I'm unable to figure out why this is happening. Is this configured by Spring? Thanks in advance.
Controller:
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(#RequestBody IndividualProviderDto individualProviderDto) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
HttpStatus httpStatus = null;
try {
individualProviderService.saveIndividualProvider(individualProviderDto);
httpStatus = HttpStatus.CREATED;
} catch (ConstraintViolationException e) {
httpStatus = HttpStatus.CONFLICT;
}
return new ResponseEntity<String>(headers, httpStatus);
}
Service:
public void saveIndividualProvider(IndividualProviderDto individualProviderDto) {
IndividualProvider individualProvider = individualProviderDtoToIndividualProviderMapper.map(individualProviderDto);
individualProviderRepository.save(individualProvider);
}
Stack:
2014-06-24 09:15:36,117 ["http-bio-9001"-exec-6] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry 'xxx#gmail.com' for key 'UK_thwi4ibpanesigdfbx3iqt0bg'
Servlet.service() for servlet [bham] in context with path [/cds] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception
.ConstraintViolationException: could not execute statement; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statemen
t] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'xxx#gmail.com' for key 'UK_thwi4ibpanesigdfbx3iqt0bg'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2825)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2350)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
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.$Proxy97.persist(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:262)
at com.sun.proxy.$Proxy96.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:369)
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.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
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.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:105)
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.$Proxy98.save(Unknown Source)
at com.mycompany.bham.service.provider.IndividualProviderServiceImpl.saveIndividualProvider(IndividualProviderServiceImpl.java:82)
at com.mycompany.bham.web.IndividualProviderController.createFromJson(IndividualProviderController.java:88)
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)
You may want to use Exception Handler of Spring http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Here an example code:
#Controller
public class ExceptionHandlingController {
// #RequestHandler methods
...
// Exception handling methods
// Convert a predefined exception to an HTTP Status code
#ResponseStatus(value=HttpStatus.CONFLICT, reason="Data integrity violation") // 409
#ExceptionHandler(DataIntegrityViolationException.class)
public void conflict() {
// Nothing to do
}
// Specify the name of a specific view that will be used to display the error:
#ExceptionHandler({SQLException.class,DataAccessException.class})
public String databaseError() {
// Nothing to do. Returns the logical view name of an error page, passed to
// the view-resolver(s) in usual way.
// Note that the exception is _not_ available to this view (it is not added to
// the model) but see "Extending ExceptionHandlerExceptionResolver" below.
return "databaseError";
}
// Total control - setup a model and return the view name yourself. Or consider
// subclassing ExceptionHandlerExceptionResolver (see below).
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception exception) {
logger.error("Request: " + req.getRequestURL() + " raised " + exception);
ModelAndView mav = new ModelAndView();
mav.addObject("exception", exception);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
}
I have these classes:
public class UserCredential {
#NotNull(message ="The password must not be null !")
#NotEmpty(message="The password must not be empty !")
private String password;
#NotNull(message ="The email/name must not be null !")
#NotEmpty(message="The email/name must not be empty !")
private String email;
//GETTERS AND SETTERS
}
and my real Entity is like this :
#Entity
public class BlogUser {
#Id
#GeneratedValue
private Long id;
private String name;
private String email;
private String password;
private String website;
//GETTERS AND SETTERS
}
I use Spring and In my repository tier I have a method like this :
public boolean isValidLogin(UserCredential userCredential) {
List <BlogUser> list = em.createQuery("SELECT c FROM BlogUser c WHERE c.email = " + userCredential.getEmail()+ " AND c.password = " + userCredential.getPassword()).getResultList();
if (list.size() == 1) {
return true;
} else {
return false;
}
}
but when my program is going to execute the query I get this error:
HTTP Status 500 - Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
type Exception report
message Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:180)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:277)
com.sts.repository.UserRepositoryImpl.isValidLogin(UserRepositoryImpl.java:52)
com.sts.service.UserServiceImpl.isValidLogin(UserServiceImpl.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
com.sun.proxy.$Proxy44.isValidLogin(Unknown Source)
com.sts.controller.Welcome.loginUser(Welcome.java:53)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:180)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:61)
org.hibernate.loader.Loader.getResultSet(Loader.java:2040)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1837)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
org.hibernate.loader.Loader.doQuery(Loader.java:900)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
org.hibernate.loader.Loader.doList(Loader.java:2526)
org.hibernate.loader.Loader.doList(Loader.java:2512)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
org.hibernate.loader.Loader.list(Loader.java:2337)
org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:356)
org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:268)
com.sts.repository.UserRepositoryImpl.isValidLogin(UserRepositoryImpl.java:52)
com.sts.service.UserServiceImpl.isValidLogin(UserServiceImpl.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
com.sun.proxy.$Proxy44.isValidLogin(Unknown Source)
com.sts.controller.Welcome.loginUser(Welcome.java:53)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:180)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
org.postgresql.util.PSQLException: ERROR: column "mehdi" does not exist
Position: 286
org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157)
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1886)
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:555)
org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:302)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:56)
org.hibernate.loader.Loader.getResultSet(Loader.java:2040)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1837)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
org.hibernate.loader.Loader.doQuery(Loader.java:900)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
org.hibernate.loader.Loader.doList(Loader.java:2526)
org.hibernate.loader.Loader.doList(Loader.java:2512)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
org.hibernate.loader.Loader.list(Loader.java:2337)
org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:356)
org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:268)
com.sts.repository.UserRepositoryImpl.isValidLogin(UserRepositoryImpl.java:52)
com.sts.service.UserServiceImpl.isValidLogin(UserServiceImpl.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
com.sun.proxy.$Proxy44.isValidLogin(Unknown Source)
com.sts.controller.Welcome.loginUser(Welcome.java:53)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:180)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
This is the my example query trace:
Hibernate:
select
tuser0_.id as id1_1_,
tuser0_.email as email2_1_,
tuser0_.name as name3_1_,
tuser0_.password as password4_1_,
tuser0_.website as website6_1_
from
BlogUser tuser0_
where
tuser0_.email=mehdi
and tuser0_.password=123456
you think, what is the problem ???
When building your query without parameters (it's a bad idea) you need to take care of quote and type convertion etc...
List <BlogUser> list = em.createQuery("SELECT c FROM BlogUser c WHERE c.email = '" + userCredential.getEmail()+ "' AND c.password = '" + userCredential.getPassword()+"'").getResultList();
A better solution is to use parameters :
List <BlogUser> list = em.createQuery("SELECT c FROM BlogUser c WHERE c.email = :email AND c.password = :pwd")
.setParameter("email",userCredential.getEmail())
.setParameter("pwd",userCredential.getPassword())
.getResultList();
Like ben75's answer, it is preferred to use parameters instead of modifying the query String.
The other problem is that you may be trying to get a list of BlogUser just to count them. Imagine that the BlogUser has a eager list of attributes. You may end up doing many SELECTS just to see if there is any BlogUser with the desired email/password.
It is better if you delegate the counting part to the database.
public boolean isValidLogin(UserCredential userCredential) {
Integer count = (Integer)em.createQuery(
"SELECT count(c.id) "+
"FROM BlogUser c " +
"WHERE c.email = :email AND c.password = :pwd")
.setParameter("email",userCredential.getEmail())
.setParameter("pwd",userCredential.getPassword())
.getSingleResult();
if (count == 1) {
return true;
} else {
return false;
}
}
I would like to get the id of the currently logged in user and use it to access their specific user page.
To implement that I have been able to get the current logged in user's name using:
#RequestMapping(value = "/main/home", method = RequestMethod.GET)
public String getHomePage(Model model, Principal principal, HttpServletRequest
request) {
try {
CustomUser customUser =
(CustomUser)SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
request.getSession().setAttribute("name",
customUser.getName());
request.getSession().setAttribute("userId",
customUser.getUserId());
request.getSession().setAttribute("user", customUser);
} catch (Exception e) {
e.printStackTrace();
}
return "/main/home";
}
Then in the JSP page, I'm using the following code to try to get the user's page based on their id:
<c:url value="/main/user/?userId=${user.userId}" var="url"/><a href="<c:out
value='${url}'/>">User Page</a>
But this implementation is not working. When I click on the user page, I receive the following error:
java.lang.IllegalArgumentException: id to load is required for loading
org.hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:87)
org.hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:59)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2421)
org.hibernate.internal.SessionImpl.get(SessionImpl.java:974)
com.project.myapp.dao.UserDAO.getUserByID(UserDAO.java:91)
com.project.myapp.dao.UserDAO$$FastClassByCGLIB$$b394c410.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
com.project.myapp.dao.UserDAO$$EnhancerByCGLIB$$232ac7e1.getUserByID(<generated>)
com.project.myapp.service.UserServiceImpl.getUserByID(UserServiceImpl.java:54)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
$Proxy314.getUserByID(Unknown Source)
com.project.myapp.controller.UserController.getUserPage(UserController.java:70)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I would like any insight into knowing why I cannot request the user's id but I can get the user's name.
I have this problem: I can write to a Postgis table with a geography type column and the data is entered correctly. When I try to get it back, I get a java.lang.IllegalArgumentException: Can't convert object of type org.postgresql.util.PGobject
I'm using Hibernate Spatial 4.0M1, Postgis 2.0.2, Postgresql 9.1.7 and Spring 3.2, Postgis-jdbc 2.0.2 and I tried also 1.5.2 and Postgresql-jdbc 9.1-901.
This is the relevant part of my class
public class Poi {
#Id
#GeneratedValue(generator="t_pois_poisid_seq")
private long poisid;
#Column(name="name")
private String name;
#Column(name="userid")
private int owner;
//#Column(columnDefinition = "Geometry", name="location")
#Type(type="org.hibernate.spatial.GeometryType")
private Point location;
public Poi(){}
public Poi(String name, int owner, String wktPoint){
this.name = name;
this.owner = owner;
WKTReader fromText = new WKTReader();
Geometry geom = null;
try{
geom = fromText.read(wktPoint);
}catch(ParseException e){
throw new RuntimeException("Not a WKT string:" + wktPoint);
}
if (!geom.getGeometryType().equals("Point")) {
throw new RuntimeException("Geometry must be a point. Got a " + geom.getGeometryType());
}
//geom.setSRID(4326);
this.location = (Point) geom;
}
}
And this is the error I get
java.lang.IllegalArgumentException: Can't convert object of type org.postgresql.util.PGobject
org.hibernate.spatial.dialect.postgis.PGGeometryValueExtractor.toJTS(PGGeometryValueExtractor.java:99)
org.hibernate.spatial.dialect.AbstractJTSGeometryValueExtractor.extract(AbstractJTSGeometryValueExtractor.java:42)
org.hibernate.spatial.dialect.AbstractJTSGeometryValueExtractor.extract(AbstractJTSGeometryValueExtractor.java:37)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:269)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:265)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:238)
org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:357)
org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2807)
org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1545)
org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1477)
org.hibernate.loader.Loader.getRow(Loader.java:1377)
org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:644)
org.hibernate.loader.Loader.doQuery(Loader.java:854)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:293)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:263)
org.hibernate.loader.Loader.loadEntity(Loader.java:1977)
org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:82)
org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:72)
org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3821)
org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:458)
org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:427)
org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:204)
org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:260)
org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:148)
org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1075)
org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:175)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2421)
org.hibernate.internal.SessionImpl.get(SessionImpl.java:971)
com.prismio.pois.api.repository.HibernatePoiRepository.findOne(HibernatePoiRepository.java:30)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
$Proxy24.findOne(Unknown Source)
com.prismio.pois.api.controller.PoiController.getUser(PoiController.java:40)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
If anyone is interested: the problem is that PostGIS returns a PGObject from a column type Geography and not PGGeometry, so the cast to PGgeometry is not possible. The solution I found using jdbcTemplate (and not Hibernate) is to cast the field from the resultset to PGObject and then create a PGGeometry like this:
PGgeometry geo = new PGgeometry(myPGObject.getValue());
Doing this, geo.getValue() returns a string in the form SRID=4326;POINT(40.70686417491799 -74.01572942733765) which is what I wanted. I could do the query using ST_AsText but it loses precision. I don't know Hibernate well enough to propose a solution to this, but this is enough for my use case.