Cannot cast response from Hibernate to List of objects - java

Hibernate outputs list of list of values instead of list of objects
I referred to some samples which leads me to the same way that I have implemented already.
Hibernate sample
Here my problem,
public List<Loan> getLoans(Date fromDate, Date toDate) {
factory = DbSessionManager.getSessionFactory("core");
Session session = factory.openSession();
Transaction tx = null;
List<Loan> loans = null;
try{
session.createCriteria(Loan.class).list();
tx = session.beginTransaction();
Query query = session.getNamedQuery("getLoansBetweenDates").setDate("fromDate", fromDate).setDate("toDate", toDate);
loans = query.list();
for (Iterator iterator = loans.iterator(); iterator.hasNext();) {
Loan loan = (Loan) iterator.next();
System.out.println(loan.getLoanId());
}
tx.commit();
}catch (HibernateException he) {
if(tx!=null) tx.rollback();
he.printStackTrace();
}
return loans;
}
Error when tried to cast to Loan:
SEVERE: Servlet.service() for servlet [TM_Service] in context with path [/TM_Service] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to model.core.Loan] with root cause java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to model.core.Loan
at utility.LoanManager.getLoans(LoanManager.java:75)
at controller.LoanController.getLoan(LoanController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
In other words, the above code when exposed as a web service, without any casting, I get the following output. Looks like a list of - list of values
[
[
"137",
15,
"open",
null
],
[
"147",
17,
"open",
null
],
[
"157",
16,
"open",
null
]
]
I'm expecting the following output,
[
{
"loanId":"137",
"customerId":15,
"status":"open",
"comments":null
},
{
"loanId":"147",
"customerId":17,
"status":"open",
"comments":null
},
{
"loanId":"157",
"customerId":16,
"status":"open",
"comments":null
}
]
Pojo
#NamedNativeQueries({
#NamedNativeQuery(
name = "getLoansBetweenDates",
query = "select * from tm_core.loan where tm_core.loan.loan_id in "
+ "(select tm_core.loan.loan_id from tm_core.loan inner join tm_core.transaction " +
"on tm_core.loan.loan_id = tm_core.transaction.loan_id " +
"where " +
"loan_status = 'open' and " +
"category = 'principal' and " +
"date >= :fromDate and " +
"date <= :toDate " +
"order by date asc)"
)
})
#Entity
#Table(name="loan")
public class Loan implements Serializable{
#Id
#Column(name="loan_id", nullable=false, unique=true)
String loanId;
#ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name="customer_id", nullable = false)
#JsonBackReference
Customer customer;
#Column(name="loan_status")
String loanStatus;
#Column(name="comments")
String comments;
}
Should I implement object mapper which I feel as messy option? Is there any way to tweak the Hibernate output so that the response will looks like list of objects, instead of a 'list of - list of values'
My project source code

Related

java.lang.ClassCastException While Using Projection in hibernate 4

I am using hibernate to fetch only specific fields from and Entity. For that I am using Criteria API and using projections. I am getting ClassCastExcepiton when I try to traverse the list returned by the list() method of the Criteria API.
Please help me in finding out the missing of the below code.
#RequestMapping("/pResult")
public String retrieveLpnOnPagination(Model model) {
for (int i = 1; i <= 9; i += 3) {
List<MyLpn> lpns = lpnService.retrievePaginatedResult(i, 3,new String[]{"lpnId","status","whse"});
for (MyLpn lpn : lpns)
System.out.println(lpn.toString());
System.out.println();
}
return "home";
}
DaoImpl method
public List<MyLpn> retrievePResult(int i, int j, String[] projectionFields) {
Session currentSession = sessionFactory.getCurrentSession();
Criteria createCriteria = currentSession.createCriteria(MyLpn.class);
ProjectionList projectionList = Projections.projectionList();
for (String field : projectionFields)
projectionList.add(Projections.property(field));
createCriteria.setProjection(projectionList);
List<MyLpn> list = createCriteria.list();
for (MyLpn lpn : list)
System.out.println(lpn.toString());
return list;
}
Exception
SEVERE: Servlet.service() for servlet [spring] in context with path [/MyW2014] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.w.model.MyLpn] with root cause
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.w.model.MyLpn
at com.wmos.dao.LpnDaoImpl.retrievePResult(LpnDaoImpl.java:88)
at com.w.service.LpnService.retrievePaginatedResult(LpnService.java:43)
at com.wmos.service.LpnService$$FastClassBySpringCGLIB$$4e814eab.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.wmos.service.LpnService$$EnhancerBySpringCGLIB$$bec224d4.retrievePaginatedResult(<generated>)
at com.wmos.controller.LpnController.retrieveLpnOnPagination(LpnController.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1136)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Thank you.
Try this
createCriteria.setResultTransformer(Transformers.aliasToBean(MyLpn.class));
List<MyLpn> list = createCriteria.list();

Cassandra Exception : #Table annotation not found on the class

I am new to cassandra database. I am trying to map a table to a java class.
My java class:
#Table("user")
public class User implements Serializable
{
#PrimaryKey
#Column(value = "id")
private int id;
#Column(value = "first_name")
private String firstName;
//setters and getters
}
Dao class:
public class UserDaoImpl {
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect("agtr_api");
MappingManager manager = new MappingManager(session);
Mapper<User> mapper = manager.mapper(User.class);
public User getUserById(int id){
User u = mapper.get(id);
return u;
}
}
When i run my application on server, It throws following exception:
SEVERE: Servlet.service() for servlet [spring] in context with path
[/aggregator-api] threw exception [Request processing failed; nested
exception is java.lang.IllegalArgumentException: #Table annotation was
not found on class com.data.User] with root cause
java.lang.IllegalArgumentException: #Table annotation was not found on
class com.data.User at
com.datastax.driver.mapping.AnnotationChecks.getTypeAnnotation(AnnotationChecks.java:43)
at
com.datastax.driver.mapping.AnnotationParser.parseEntity(AnnotationParser.java:76)
at
com.datastax.driver.mapping.MappingManager.getMapper(MappingManager.java:226)
at
com.datastax.driver.mapping.MappingManager.mapper(MappingManager.java:182)
at com.etl.aapi.common.dao.UserDaoImpl.(UserDaoImpl.java:19)
at
com.etl.aapi.common.controller.UserController.a(UserController.java:13)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
You can declare also you keyspace name. Try to use the complete syntax as below:
#Table(keyspace = "yourKeyspace", name = "yourTable")
The "#Annotation" error is misleading as you rightly guess and the exception does not directly tell what is the actual error. The underlying problem would always be in your Domain/Model class fields/columns definition such as column name missing, miss match etc, always watch out your Domain/Model class.
Besides, If you use Achilles library and #Table annotation from Achilles, you will not get correct error. As a workaround you can additionally use #Table annotation from DataStax driver which will try to throw you more details in the exception stack trace.

I am trying following query and getting unexpected token : in exception

public boolean insert(Product product){
boolean result = true;
Transaction tx = null;
int quantity=0;
try {
tx = session.getTransaction();
tx.begin();
Query query=session.createQuery("update Stock s set s.quantity=s.quantity+100");
query.executeUpdate();
session.saveOrUpdate(product);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
result=false;
} finally {
session.close();
}
return result;
}
select ,save and delete query are working successfully but This exception I am getting only in while update the record....
I want to save the record in Product Table and as well as update Stock Table
BELOW IS MY EXCEPTION
org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:8: unexpected token: in
Sep 12, 2015 10:34:41 AM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:8: unexpected token: in
line 1:8: unexpected token: in
at org.hibernate.hql.internal.antlr.HqlBaseParser.updateStatement(HqlBaseParser.java:239)
at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:169)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:295)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:131)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:93)
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:1836)
at in.edu.pondiuni.service.ProductService.insert(ProductService.java:23)
at in.edu.pondiuni.controller.ProductServlet.processRequest(ProductServlet.java:53)
at in.edu.pondiuni.controller.ProductServlet.doGet(ProductServlet.java:91)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
If sure of the executed query, I would try using another package name, in is a reserved keyword and that might be the issue, that would correspond to position 8:
UPDATE in.edu.pondiuni.xxx.Stock
^
8
To do so, a search and replace in your codebase of in.edu.pondiuni should do the job, you can replace it with edu.pondiuni for example.

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.sakhnin.classes.MonthlySummary

I'm trying to print all date in this MonthlyReport and got this exception.
SEVERE: Servlet.service() for servlet showMettingReports threw
exception java.lang.ClassCastException: [Ljava.lang.Object; cannot be
cast to com.sakhnin.classes.MonthlySummary at
org.apache.jsp.jspFiles.showMettingReports_jsp._jspService(showMettingReports_jsp.java:150)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at
org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at
org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at
org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at com.sakhnin.implementations.Controller.doGet(Controller.java:140)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
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:506)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
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:537)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
com.sakhnin.classes.MonthlySummary
MonthlySummary.java
public class MonthlySummary {
#Id
private String Date;
private int Cost;
private String Place;
private String Start;
private String End;
private String Description;
private int MentorID;
public MonthlySummary() {
// TODO Auto-generated constructor stub
}
public MonthlySummary(String place, String date, String start, String end,
String description, int cost, int mentorID) {
super();
Place = place;
Date = date;
Start = start;
End = end;
Description = description;
Cost = cost;
MentorID = mentorID;
}
MonthlySummaryIMP.java
public List<MonthlySummary> getMentorReportsById(int id) {
List<MonthlySummary> reports=null;
try{
session = factory.openSession();
session.beginTransaction();
// Fetch all active coupons whose businesses' parent's category is as got in the argument
SQLQuery query = session.createSQLQuery("SELECT * FROM MonthlySummary WHERE MentorID="+id );
reports = query.list();
closeSession();
}
catch(HibernateException e){
System.err.println(e.getMessage());
}
catch(Exception e){
System.err.println(e.getMessage());
}
return reports;
}
jsp file
<tbody>
<%
List<MonthlySummary> m = (List<MonthlySummary>)request.getSession().getAttribute("meetingsReports");
for(MonthlySummary report : m) {
%>
<td>Date<%=report.getDate() %></td>
<td>Date<%=report.getPlace()%></td>
<td>Date<%=report.getStart()%></td>
<td>Date<%=report.getEnd()%></td>
<td>Date<%=report.getDescription() %></td>
<td>Date<%=report.getCost()%></td>
<%
}
%>
</tbody>
To avoid such ClassCastException, you need to add Entity into your query object.
Try below--
SQLQuery query = session.createSQLQuery("SELECT * FROM MonthlySummary WHERE MentorID="+id );
query.addEntity(MonthlySummary.class);
reports = query.list();
--rest of code
As your stack trace suggests that the its trying to cast List of MonthlySummary but actually it cannot understand the left hand object to complete this process.
This kind of strange because if you would have not set the HTTPSession attribute on the first hand it should give you Null Pointer Exception.
Are you sure that you are not setting any attribute with that key, my assumption here is that you are setting some other object in that key.
Please use the trick mentioned by Sighr and that should do the magic for you.

Cannot execute select statement in hibernate

I have an action that should select a row from a table using the id:
#RequestMapping("/test/{userId}")
#ResponseBody
public void testUserSettings(#DestinationVariable Integer userId){
System.out.println("test");
Session session = sessionFactory.openSession();
Query query = session.createQuery("select us.settings from UserSettings us"
+ " where us.userId = :userId");
Transaction transaction = null;
try {
transaction = session.beginTransaction();
query.setParameter("userId", userId);
query.executeUpdate();
transaction.commit();
} catch (HibernateException e) {
if (transaction != null)
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
It invokes the method because "test" is printed. The problem is in the statement. For some reason I get the following output in the console:
org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for select queries [select us.settings from com.musala.ving.entities.UserSettings us where us.userId = :userId]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.errorIfSelect(QueryTranslatorImpl.java:324)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:444)
at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:379)
at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1286)
at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:118)
at com.musala.ving.controllers.UserSettingsController.testUserSettings(UserSettingsController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
You are calling query.executeUpdate(); for a select query. Try using query.list(), or query.uniqueResult() instead.
query.uniqueResult() should be used if you expect a single result.
Javadoc excerpt for Query#list():
Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[].
Javadoc excerpt for Query#uniqueResult():
Convenience method to return a single instance that matches the query, or null if the query returns no results.
Also, transaction.commit(); should not be necessary since this query doesn't update the database.
#RequestMapping("/test/{userId}")
#ResponseBody
public void testUserSettings(#DestinationVariable Integer userId){
System.out.println("test");
Session session = sessionFactory.openSession();
Query query = session.createQuery("select us.settings from UserSettings us"
+ " where us.userId = :userId");
Transaction transaction = null;
try {
transaction = session.beginTransaction();
query.setParameter("userId", userId);
query.list();
transaction.commit();
} catch (HibernateException e) {
if (transaction != null)
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
I am using hibernate with hql (in conjunction with spring mvc, if that matters) and fixed the issue by doing the following:
String hql = "select clientId from Cart where cartId = :val" ;
Query query = getSession().createQuery(hql);
query.setParameter("val", cartId);
//int result = query.executeUpdate(); OLD VERSION. REPLACED WITH THE LINE BELOW:
int result = query.getFirstResult();
return result;
So for me getFirstResult() solved the problem.
query.executeUpdate();
you do a update of an select query !?
How the error message says... "Not supported for select queries"
use query.execute(); or what the correct method is...

Categories

Resources