Cannot execute select statement in hibernate - java

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...

Related

Cannot cast response from Hibernate to List of objects

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

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.

Hibernate DAO get method does not work if called via REST, does otherwise

I wonder if anyone can explain why the following code in a DAO in a Spring and Hibernate web application:
#Override
public Book get(Integer bookId) {
logger.info(BookDAOImpl.class.getName() + ".get() method called.");
Session session = sessionFactory.openSession();
try {
System.out.println("Book : " + bookId);
Book book = (Book) session.get(Book.class, bookId);
return book;
}
finally {
session.close();
}
}
Will work perfectly well inside its parent web application but when called via REST through a controller and service class:
// Gets a Book via REST.
#RequestMapping(value="/book/{bookId}", method=RequestMethod.GET)
public #ResponseBody Object getBook(#PathVariable("bookId") String bookId) {
logger.info(RestController.class.getName() + ".getBook() method called.");
if (bookIdValid(bookId)) {
Book book = bookService.get(Integer.parseInt(bookId));
System.out.println("ABook " + book.toString());
return book;
}
else {
Messages messages = new Messages();
messages.addMessage(messageSource.getMessage("bookId.required", null, null));
return messages;
}
}
The line Book book = (Book) session.get(Book.class, bookId); returns null.
Line 53 of BookDAOImpl is line return bookId == book.getBookId().intValue(); in the method below:
#Override
public boolean check(Integer bookId) {
logger.info(BookDAOImpl.class.getName() + ".check() method called.");
try {
Book book = this.get(bookId);
return bookId == book.getBookId().intValue();
}
catch(IndexOutOfBoundsException e) {
return false;
}
}
The stacktrace is:
Book : 78
INFO|12 07 2015|22 07 16|http-apr-8080-exec-123|library.controller.PersonController| - library.controller.ExceptionController.exception() method called.
null
library.dao.BookDAOImpl.check(BookDAOImpl.java:53)
library.service.BookServiceImpl.check(BookServiceImpl.java:32)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:201)
com.sun.proxy.$Proxy571.check(Unknown Source)
library.controller.RestController.bookIdValid(RestController.java:127)
library.controller.RestController.getBook(RestController.java:102)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
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:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2451)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2440)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:744)
library.interceptor.ClientInterceptor.afterCompletion() method completed: GET: /Library/rest/book/78?null at 12 07 2015 # 22 07 ended with HTTP code: 500.
It looks like session.get(Book.class, bookId) is returning null - your database likely does not contain book 78. Do you have a create book endpoint you can use to insert into the database prior to hitting the get endpoint?

More than one row with the given identifier was found: 1, for class: com.model.Diagnosis

Below is the model, service implementation and the error trace of my code.
Model class:
#Entity
#Table(name = "ph_diagnosis_history")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id",scope=Diagnosis.class)
public class Diagnosis extends AbstractEntity {
#Column(name = "diagnosis_notes", length=255)
#Length(max = 255, message = IprProp.MAX_LEN_255_MSG)
private String diagnosisNote;
#Enumerated(EnumType.STRING)
private DiagnosisTypeEnum type;
#Temporal(TemporalType.DATE)
#Column(name = "diagnosis_date")
#JsonSerialize(using = JsonDateSerializer.class)
private Date diagnosisDate;
#ManyToOne
#JoinColumn(name = "patient_chart_id")
private PatientChart patientChart;
public String getDiagnosisNote() {
return diagnosisNote;
}
public void setDiagnosisNote(String diagnosisNote) {
this.diagnosisNote = diagnosisNote;
}
public DiagnosisTypeEnum getType() {
return type;
}
public void setType(DiagnosisTypeEnum type) {
this.type = type;
}
public Date getDiagnosisDate() {
return diagnosisDate;
}
public void setDiagnosisDate(Date diagnosisDate) {
this.diagnosisDate = diagnosisDate;
}
public PatientChart getPatientChart() {
return patientChart;
}
public void setPatientChart(PatientChart patientChart) {
this.patientChart = patientChart;
}
}
My service:
public Diagnosis updateDiagnosis(IPRDTO clientDto, Long userId,
Long patientChartId, DiagnosisDTO diagnosisDTO, Long diagnosisId) throws Exception {
Diagnosis diagnosis = diagnosisRepository.findOne(diagnosisId);
if (diagnosis!=null){
if(diagnosis.getType().equals(DiagnosisTypeEnum.WORKING)){
BeanCopyUtil.copyProperties(diagnosisDTO, diagnosis, true);
return this.diagnosisRepository.saveAndFlush(diagnosis);
}
else{
throw new BusinessException("updateDiagnosisValidation");
}
}
throw new BusinessException("noDiagnosis");
}
My stack trace:
[2014-09-08 11:34:08,148] INFO com.zurelsoft.ipr.service.IDiagnosisService- Logged In User Id [1]:Started updateDiagnosis
diagnosis id 2
[2014-09-08 11:34:08,969] INFO org.hibernate.event.internal.DefaultLoadEventListener- HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
[2014-09-08 11:34:09,001] ERROR com.zurelsoft.ipr.service.IDiagnosisService- Logged In User Id [1]:Error Occurred updateDiagnosis
org.springframework.orm.jpa.JpaSystemException: org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis; nested exception is javax.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
[2014-09-08 11:34:09,006] ERROR com.zurelsoft.ipr.client.DiagnosisWebService- org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy85.findOne(Unknown Source)
com.zurelsoft.ipr.service.impl.DiagnosisServiceImpl.updateDiagnosis(DiagnosisServiceImpl.java:76)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.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.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:51)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy86.updateDiagnosis(Unknown Source)
com.zurelsoft.ipr.client.DiagnosisWebService.updateDiagnosis(DiagnosisWebService.java:98)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.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.doPut(FrameworkServlet.java:849)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
I get this HibernateException in this line alhough my table has now two rows with the same id.
Diagnosis diagnosis = diagnosisRepository.findOne(diagnosisId);
Please anyone help me with my mistake. What can be probable error in my code.
Hy, It woks for me:
Seems I have two choices: either cascade all and delete orphan on the one-to-one relationship, or explicitly call my repository class to look up and save the original Sheet every time I remove its relationship with Plate. I opted for the first choice and added this to the plate class:
#OneToOne(mappedBy = "plate", cascade = CascadeType.ALL, orphanRemoval = true)
https://stackoverflow.com/a/32636186/3255595
From Spring documentation:
T findOne(ID id)
Retrieves an entity by its id.
Seem that diagnosisId is not a primary key.
it sounds like you have more than one row in the database with the same id values!
Are you sure your id is really unique in the DB ?
Hibernate Exception
More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
tells that hibernate query executes returns more than one row (i.e 2) of class Diagnosis Please enable SQL logging and execute the select by hand and see what it returns

java.sql.SQLException: ORA-01008: not all variables bound using Mybatis 3

So I'm using Mybatis 3 to make procedure calls. This is the first time I'm using this method to make calls to an oracle database (the other times it was a mysql database) and i get the above mentioned error. I have never had an issue making mysql database calls in the same fashion is there something special i need to do with oracle? It seems that this error message generally means that the number of parameters or '?' don't match the what's being set, but as can be seen from my xml file I am setting all the parameters.
10:07:22,079 [DEBUG] {call.authenticateCmplnr} - ooo Using Connection [oracle.jdbc.driver.OracleConnection#543d1aa8]
10:07:22,083 [DEBUG] {call.authenticateCmplnr} - ==> Preparing: CALL TDU_LOGIN_USER_CHECK( ?, ?, ?, ?, ? )
10:07:22,129 [DEBUG] {call.authenticateCmplnr} - ==> Parameters: m440109(String), TDU(String)
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.sql.SQLException: ORA-01008: not all variables bound
### The error may exist in com/cmplnr/datasource/dataservice.xml
### The error may involve call.authenticateCmplnr-Inline
### The error occurred while setting parameters
### SQL: CALL TDU_LOGIN_USER_CHECK( ?, ?, ?, ?, ? )
### Cause: java.sql.SQLException: ORA-01008: not all variables bound
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:107)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:98)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:62)
at com.cmplnr.integration.AuthenticationServiceImpl.authorizeAccess(AuthenticationServiceImpl.java:80)
at com.cmplnr.integration.AuthenticationServiceImpl.authenticateCmplnr(AuthenticationServiceImpl.java:53)
at com.cmplnr.control.TDU_Control.test(TDU_Control.java:24)
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.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
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.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1813)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLException: ORA-01008: not all variables bound
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:590)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1973)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1119)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2191)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:2064)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2989)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:658)
at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:736)
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.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:55)
at $Proxy14.execute(Unknown Source)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:56)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:70)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:57)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:259)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:132)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:105)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:104)
... 34 more
My implementation
private User authorizeAccess(String id){
SqlSession session = sqlSessionFactory.openSession();
Map<String,Object>params = new HashMap<String,Object>();
params.put("id", id);
params.put("cycleType", "TDU");
User user = null;
try{
user = session.selectOne("call.authenticateCmplnr", params);
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
session.close();
}
return user;
}
The xml file
<mapper namespace="call">
<resultMap id = "userMap" type="com.cmplnr.core.User">
<result property="id" column="ATTRIBUTE1"/>
<result property="fullName" column="USER_NAME"/>
</resultMap>
<select id = "authenticateCmplnr" parameterType="java.util.Map">
CALL TDU_LOGIN_USER_CHECK(
#{id, mode=IN, jdbcType=VARCHAR},
#{cycleType, mode=IN, jdbcType=VARCHAR},
#{cursor, mode=OUT, jdbcType=CURSOR, resultMap=userMap},
#{errcode, mode=OUT, jdbcType=INTEGER},
#{errmsg, mode=OUT, jdbcType=VARCHAR}
)
</select>
</mapper>
Can you try putting your OUT parameters to the Map, with null values?
You can see this possibly dupe answer.
private User authorizeAccess(String id){
SqlSession session = sqlSessionFactory.openSession();
Map<String,Object>params = new HashMap<String,Object>();
params.put("id", id);
params.put("cycleType", "TDU");
params.put("cursor", null);
params.put("errcode", null);
params.put("errmsg", null);
User user = null;
try{
user = session.selectOne("call.authenticateCmplnr", params);
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
session.close();
}
return user;
}

Categories

Resources