I am getting org.springframework.dao.InvalidDataAccessResourceUsageException exception while fetching data from multiple tables in getMenusByRole. My query is correct and giving expected result on database.
Following is code snippet-
UserDaoImpl.java
package com.msoft.crm.daos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.w3c.dom.ls.LSInput;
import com.msoft.crm.entities.Users;
#Repository("UserDao")
public class UserDaoImpl implements UserDao {
#PersistenceContext
private EntityManager entityManager;
public String original,recipientAddress,firstName,userName;
#Override
public List<Users> getAllUsers() {
return new ArrayList<Users>();
}
#Override
public List<Users> validateLogin(String username, String password) {
String hql = "from Users u where u.username = :p_username and u.userPassword = :p_password";
Query q = entityManager.createQuery(hql);
q.setParameter("p_username", username);
q.setParameter("p_password", password);
List<Users> users = q.getResultList();
System.out.println("users : " + users);
return users;
}
#Override
public List<Users> getMenusByRole(long userId) {
String hql = " select ur.role_id ,ur.role_name ,ur.speciality ,ms.section_id ,ms.section_name ,ms.section_position ,"
+ "ms.section_icon ,mi.menu_id ,mi.menu_name ,mi.menu_action ,mi.menu_position ,mi.parent_menu_id "
+ "from MenuPrivileges mp inner join UserRoles ur on mp.role_id = ur.role_id "
+ "inner join MenuItems mi on mp.menu_id = mi.menu_id "
+ "inner join MenuSections ms on mi.section_id = ms.section_id "
+ "where mi.active_ind = '1' and mp.visible_ind = '1' "
+ "and mp.role_id = (select role_id from crm_users where user_id = :user_id) order by ms.section_position asc";
Query q = entityManager.createNativeQuery(hql);
q.setParameter("user_id", userId);
List<Users> l = q.getResultList();
System.out.println("l : " + l);
return l;
}
}
MenuPrivileges.java
package com.msoft.crm.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="crm_menu_privileges")
public class MenuPrivileges {
#Id
#Column
private int role_id;
#Column
private int menu_id;
#Column
private String visible_ind;
public MenuPrivileges() {
this(0,0,"");
}
public MenuPrivileges(int role_id, int menu_id, String visible_ind) {
this.role_id = role_id;
this.menu_id = menu_id;
this.visible_ind = visible_ind;
}
//getter and setter
}
UserRoles.java
#Entity
#Table(name="crm_user_roles")
public class UserRoles {
#Id
#Column
private int role_id;
#Column
private String role_name;
#Column
private String speciality;
// getters and setters
}
MenuItems.java
#Entity
#Table(name="crm_menu_items")
public class MenuItems {
#Id
#Column
private int section_id;
#Column
private int menu_id;
#Column
private String menu_name;
#Column
private String menu_desc;
#Column
private String menu_action;
#Column
private int menu_position;
#Column
private int parent_menu_id;
#Column
private String active_ind;
// getter and setter
}
MenuSections.javv
#Entity
#Table(name="crm_menu_sections")
public class MenuSections {
#Id
#Column
private int id_pk;
#Column
private int section_id;
#Column
private String section_name;
#Column
private String section_desc;
#Column
private String section_icon;
#Column
private int section_position;
//getter and setter
}
Following is my stacktrace where both queries are working but getting above mentioned exception for getMenuByRole.
Hibernate:
select
users0_.user_id as user_id1_5_,
users0_.aadhar_no as aadhar_n2_5_,
users0_.active_ind as active_i3_5_,
users0_.created_by_user_id as created_4_5_,
users0_.created_date_time as created_5_5_,
users0_.email as email6_5_,
users0_.fname as fname7_5_,
users0_.lname as lname8_5_,
users0_.login_status as login_st9_5_,
users0_.mname as mname10_5_,
users0_.mobile as mobile11_5_,
users0_.photo as photo12_5_,
users0_.role_id as role_id13_5_,
users0_.password as passwor14_5_,
users0_.username as usernam15_5_
from
crm_users users0_
where
users0_.username=?
and users0_.password=?
users : [Users [userId=3, roleId=1, sectionId=0, sectionPosition=0, menuId=0, menuPosition=0, parentMenuId=0, specialityId=0, username=shirin, activeInd=1, loginStatus=1, roleName=null, speciality=null, sectionName=null, sectionIcon=null, menuName=null, menuAction=null, firstName=yogiraj, lastName=kulkarni, mobileNumber=9699999999, middleName=, emailAddress=yogirajk#msoft.co.in, aadhaarNumber=123456987456, profileImg=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSEhIVFRUVFRUVFRUVFRAVFhUVFRUWFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGy0lHyUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSstLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAADAAIEBQYBBwj/xAA9EAABAwIEAwUGBAQGAwEAAAABAAIRAyEEBRIxQVFhBiJxgaETMpGxwdEUQlLwI6Lh8QczQ2JykiRTgxX/xAAbAQACAwEBAQAAAAAAAAAAAAADBAECBQAGB//EAC0RAAICAQMCBQIGAwAAAAAAAAABAhEDBBIhMUEFEyJRYTJxI1KBobHwFEKR/9oADAMBAAIRAxEAPwCwxGWADZY/NKUVCF6tmVBunyXm2dM/iFKXQWXBTFiYWqY5qjhqlSsHYwWQatVErKJUClOybOe1RKZUUboocr0SWFJ6kB6radRHFRQyCZ7REpAlNy7BOqHotZhMoAGy6MGyGZ0Unckx7DxC15y8DgomJwA5KXiZKZlHFJrkfNMI5twLKvaSh1RYnMKKHqJTRgVBwX2ia4oRK5rXHBkwtXA9OUnAKjFHJU14USoFJwXB3V1hcMdQKq8lZLoW0pYYBoKLCNg5FllNKIWlpYW0rO4arELWZbWBCZiiKK3E4boqjGYexWvxNGQs9jqcSuaJPNe0lCxWSJW47UcVhX7pWS5LREShPKcXIbioLEchJPhJSce7Z1iwAvP8wdqeSrnOcwm0qgmUjmnXAPNLsR6oshtZZHqhItso31AHu4IT6aiYkQrY07KpxhuiYZ7pUdB2yEUVtMo2GoTdSH0oRpZUnRdy5oisCm4DCmo4BCp0SVpezOGGra/FWvmi/RGiyjLQ1ostBSwgTMJS2Vs2km40iEiudhAoeJ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202d28c87440d38bd5bf4ff37c7fcc, createdBy=1, createdDate=2017-06-14 11:16:12.0]]
active ind(service):1
In get menus role user id : 3
Hibernate:
select
ur.role_id ,
ur.role_name ,
ur.speciality ,
ms.section_id ,
ms.section_name ,
ms.section_position ,
ms.section_icon ,
mi.menu_id ,
mi.menu_name ,
mi.menu_action ,
mi.menu_position ,
mi.parent_menu_id
from
MenuPrivileges mp
inner join
UserRoles ur
on mp.role_id = ur.role_id
inner join
MenuItems mi
on mp.menu_id = mi.menu_id
inner join
MenuSections ms
on mi.section_id = ms.section_id
where
mi.active_ind = '1'
and mp.visible_ind = '1'
and mp.role_id = (
select
role_id
from
crm_users
where
user_id = ?
)
order by
ms.section_position asc
2017-11-07 10:27:47.364 WARN 3116 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1146, SQLState: 42S02
2017-11-07 10:27:47.364 ERROR 3116 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : (conn:143322) Table 'crm_application.MenuPrivileges' doesn't exist
Query is: select ur.role_id ,ur.role_name ,ur.speciality ,ms.section_id ,ms.section_name ,ms.section_position ,ms.section_icon ,mi.menu_id ,mi.menu_name ,mi.menu_action ,mi.menu_position ,mi.parent_menu_id from MenuPrivileges mp inner join UserRoles ur on mp.role_id = ur.role_id inner join MenuItems mi on mp.menu_id = mi.menu_id inner join MenuSections ms on mi.section_id = ms.section_id where mi.active_ind = '1' and mp.visible_ind = '1' and mp.role_id = (select role_id from crm_users where user_id = ?) order by ms.section_position asc, parameters [3]
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at com.msoft.crm.daos.UserDaoImpl$$EnhancerBySpringCGLIB$$337e38b5.getMenusByRole(<generated>)
at com.msoft.crm.services.UserService.validateLogin(UserService.java:44)
at com.msoft.crm.controllers.LoginController.validateLogin(LoginController.java:42)
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:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
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:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2117)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1900)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2617)
at org.hibernate.loader.Loader.doList(Loader.java:2600)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
at org.hibernate.loader.Loader.list(Loader.java:2424)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1967)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
at com.msoft.crm.daos.UserDaoImpl.getMenusByRole(UserDaoImpl.java:115)
at com.msoft.crm.daos.UserDaoImpl$$FastClassBySpringCGLIB$$da03a52e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 59 more
Caused by: java.sql.SQLSyntaxErrorException: (conn:143322) Table 'crm_application.MenuPrivileges' doesn't exist
Query is: select ur.role_id ,ur.role_name ,ur.speciality ,ms.section_id ,ms.section_name ,ms.section_position ,ms.section_icon ,mi.menu_id ,mi.menu_name ,mi.menu_action ,mi.menu_position ,mi.parent_menu_id from MenuPrivileges mp inner join UserRoles ur on mp.role_id = ur.role_id inner join MenuItems mi on mp.menu_id = mi.menu_id inner join MenuSections ms on mi.section_id = ms.section_id where mi.active_ind = '1' and mp.visible_ind = '1' and mp.role_id = (select role_id from crm_users where user_id = ?) order by ms.section_position asc, parameters [3]
at org.mariadb.jdbc.internal.util.ExceptionMapper.get(ExceptionMapper.java:139)
at org.mariadb.jdbc.internal.util.ExceptionMapper.getException(ExceptionMapper.java:101)
at org.mariadb.jdbc.internal.util.ExceptionMapper.throwAndLogException(ExceptionMapper.java:77)
at org.mariadb.jdbc.MariaDbStatement.executeQueryEpilog(MariaDbStatement.java:226)
at org.mariadb.jdbc.MariaDbClientPreparedStatement.executeInternal(MariaDbClientPreparedStatement.java:233)
at org.mariadb.jdbc.MariaDbClientPreparedStatement.executeQuery(MariaDbClientPreparedStatement.java:177)
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.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
at com.sun.proxy.$Proxy81.executeQuery(Unknown Source)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
... 80 more
Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Table 'crm_application.MenuPrivileges' doesn't exist
Query is: select ur.role_id ,ur.role_name ,ur.speciality ,ms.section_id ,ms.section_name ,ms.section_position ,ms.section_icon ,mi.menu_id ,mi.menu_name ,mi.menu_action ,mi.menu_position ,mi.parent_menu_id from MenuPrivileges mp inner join UserRoles ur on mp.role_id = ur.role_id inner join MenuItems mi on mp.menu_id = mi.menu_id inner join MenuSections ms on mi.section_id = ms.section_id where mi.active_ind = '1' and mp.visible_ind = '1' and mp.role_id = (select role_id from crm_users where user_id = ?) order by ms.section_position asc, parameters [3]
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readErrorPacket(AbstractQueryProtocol.java:1144)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readPacket(AbstractQueryProtocol.java:1076)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.getResult(AbstractQueryProtocol.java:1031)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:203)
at org.mariadb.jdbc.MariaDbClientPreparedStatement.executeInternal(MariaDbClientPreparedStatement.java:224)
... 88 more
2017-11-07 10:27:47.383 ERROR 3116 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
In your getMenusByRole you are using plain SQL and not HSQL. So your table names should be crm_menu_privileges, crm_user_roles and so on.
As you are using the native query, the getResultSet() method will not return an object of User class. The other reason is HQL has not been invoked in this query and it will not be able to map the entities by its own.
In your case, the getResultSet() will return an array of Object as follows:
List<Object[]> l = q.getResultList();
And then you have to extract each element from this returned array.
For example, the Object[0] will return ur.role_id and Object[1] will return ur.role_name and so on as specified in your query.
Related
I created a Dynamic Web Project with the JPA facet running on Tomcat 9.0.24. I have a single table, called profile, in my Prostgres 10.10 database and I have a single entity "Profile" that I am trying to persist. I am using Eclipse 4.12.0.
The profile table was created using pgAdmin 4 console and it's sequence exists.
Here is my code...
Maven POM:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.7.4</version>
</dependency>
Profile entity:
package za.co.ezimax.entity;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity()
#Table(name = "profile")
public class Profile {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="first_name", nullable = false, length = 80)
private String firstName;
#Column(name="last_name", nullable = false, length = 80)
private String lastName;
#Column(name="birth_date", columnDefinition = "DATE", nullable = false)
private LocalDate birthDate;
#Column(name="sex", nullable = false)
private int sex;
#Column(name="mobile_mac", nullable = false)
private String mobileMac;
#Column(name="mobile_no", nullable = false, length = 12)
private String mobileNo;
#Column(name="registration_date", columnDefinition = "DATE", nullable = false)
private LocalDate registrationDate;
#Column(name="user_password", nullable = false, length = 80)
private char[] userPassword;
public Profile() {
}
}
Code to persist entity:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ezimax");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Profile profile = new Profile();
profile.setFirstName("Hendre");
profile.setLastName("Louw");
profile.setSex(1);
profile.setMobileMac("ff:ff:ff:ff:ff:ff:ff:ff");
profile.setMobileNo("+27832000000");
profile.setRegistrationDate(LocalDate.now());
profile.setUserPassword("password".toCharArray());
em.persist(profile);
em.getTransaction().commit();
em.close();
emf.close();
Here is the exception I am getting:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: relation "sequence" does not exist
Position: 8
Error Code: 0
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [50, SEQ_GEN]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:342)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.processExceptionForCommError(DatabaseAccessor.java:1650)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:906)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:970)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:640)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:567)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2096)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:311)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:275)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:261)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelectCall(DatasourceCallQueryMechanism.java:304)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelect(DatasourceCallQueryMechanism.java:284)
at org.eclipse.persistence.queries.DataModifyQuery.executeDatabaseQuery(DataModifyQuery.java:87)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:914)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:3349)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1895)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1877)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1842)
at org.eclipse.persistence.sequencing.QuerySequence.update(QuerySequence.java:356)
at org.eclipse.persistence.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:293)
at org.eclipse.persistence.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:75)
at org.eclipse.persistence.sequencing.DefaultSequence.getGeneratedVector(DefaultSequence.java:168)
at org.eclipse.persistence.sequencing.Sequence.getGeneratedVector(Sequence.java:267)
at org.eclipse.persistence.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:487)
at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:1109)
at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:72)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:372)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:331)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:532)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4388)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:523)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4333)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:596)
at za.co.ezimax.rest.Servlet.doGet(Servlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "sequence" does not exist
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2468)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2211)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:309)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:898)
... 55 more
As you mentioned you want to use sequences with JPA.
So you have to use the GenerationType.SEQUENCE and configure the name of the sequence:
#Id
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "sequence-generator"
)
#SequenceGenerator(
name = "sequence-generator",
sequenceName = "the_sequence_name"
)
private long id;
Replace the_sequence_name with the name of the sequence in PostgreSQL.
In your case GenerationType.AUTO translates to GenerationType.TABLE. The code is expecting that there's a table named SEQUENCE containing the values of the sequences. Since it doesn't exist, EclipseLink can't provide you with generated ids.
Either create the table (and the sequence row in it) or use a different GenerationType.
I have two classes "Project" and "Report". A Project can contain any number of Reports. When I add the first Report to a Project everything is working fine.
But when I add another Report to a Project, and use the saveOrUpdate method on the Project, I get a SQLGrammarException!
I have already checked the names of the columns.
Project mapping:
#Entity
#Table(name = "TB_PROJECT")
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name ="PROJECT_ID", unique = true, nullable = false)
private int projectID;
#Column(name = "NAME", unique = false, nullable = false)
private String name;
#Column(name = "CLIENT", unique = false, nullable = false)
private String client;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name="PROJECT_REPORTS", joinColumns= {#JoinColumn(name="PROJECT_ID", referencedColumnName="PROJECT_ID")}
, inverseJoinColumns= {#JoinColumn(name="REPORT_ID", referencedColumnName="REPORT_ID")})
private List<Report> reportList = new ArrayList<Report>();
Report mapping:
#Entity
#Table(name = "TB_REPORT", uniqueConstraints = {
#UniqueConstraint(columnNames = "REPORT_ID") })
public class Report implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name ="REPORT_ID", unique = true, nullable = false)
private int reportID;
#Column(name = "NAME", unique = false, nullable = false)
private String name;
#Column(name ="AMOUNT_COMPONENTS")
private int amountComponents;
#Column(name ="AMOUT_ACCEPTED")
private int amountAccepted;
#Column(name = "AMOUNT_REJECTED")
private int amountRejected;
#Column(name = "AMOUNT_DRAFT")
private int amountUnderDevelopment;
#Column(name = "AMOUNT_REVIEW")
private int amountUnderReview;
#Column(name = "TODELETE")
private Boolean toDelete = false;
Hibernate:
#Override
public void updatePersistentProject(Project project) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.saveOrUpdate(project);
session.getTransaction().commit();
session.close();
} catch (HibernateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Console output:
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into TB_REPORT (REPORT_ID, AMOUT_ACCEPTED, AMOUNT_COMPONENTS, AMOUNT_REJECTED, AMOUNT_DRAFT, AMOUNT_REVIEW, NAME, TODELETE) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: update TB_PROJECT set CLIENT = ?, NAME = ?, TO_DELETE = ? where PROJECT_ID=?
Hibernate: update TB_REPORT set AMOUT_ACCEPTED = ?, AMOUNT_COMPONENTS = ?, AMOUNT_REJECTED = ?, AMOUNT_DRAFT = ?, AMOUNT_REVIEW = ?, NAME = ?, TODELETE = ? where REPORT_ID=?
Hibernate: update TB_REPORT set AMOUT_ACCEPTED = ?, AMOUNT_COMPONENTS = ?, AMOUNT_REJECTED = ?, AMOUNT_DRAFT = ?, AMOUNT_REVIEW = ?, NAME = ?, TODELETE = ? where REPORT_ID=?
Hibernate: delete PROJECT_REPORTS where PROJECT_ID=?
Juli 20, 2019 10:07:40 VORM. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42601
Juli 20, 2019 10:07:40 VORM. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: FEHLER: Syntaxfehler bei »PROJECT_REPORTS«
Position: 8
Juli 20, 2019 10:07:40 VORM. org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [delete PROJECT_REPORTS where PROJECT_ID=?]]
Juli 20, 2019 10:07:40 VORM. org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [ReportServlet] in context with path [/project] threw exception
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [delete PROJECT_REPORTS where PROJECT_ID=?]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1436)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:487)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2786)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:1932)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:456)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:272)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
at dao.ProjectDAOImpl.updatePersistentProject(ProjectDAOImpl.java:70)
at logic.ReportImpl.createReport(ReportImpl.java:39)
at gui.ReportServlet.createReport(ReportServlet.java:223)
at gui.ReportServlet.doGet(ReportServlet.java:64)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at gui.LoginFilter.doFilter(LoginFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [delete PROJECT_REPORTS where PROJECT_ID=?]
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:77)
at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:95)
at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:125)
at org.hibernate.metamodel.model.domain.internal.collection.JoinTableRemovalExecutor.execute(JoinTableRemovalExecutor.java:123)
at org.hibernate.metamodel.model.domain.spi.AbstractPersistentCollectionDescriptor.remove(AbstractPersistentCollectionDescriptor.java:1245)
at org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:78)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:602)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:474)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:358)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1430)
... 39 more
Caused by: org.postgresql.util.PSQLException: FEHLER: Syntaxfehler bei »PROJECT_REPORTS«
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2468)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2211)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:309)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124)
at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:68)
... 49 more
I have following entities:
I want to delete WordSet by id and username of the user using JPA.
Here is entity declarations:
User
#Entity
#Data
#ToString(callSuper = true)
#EqualsAndHashCode(callSuper = true)
#AllArgsConstructor
#NoArgsConstructor
public class User extends AbstractModelClass {
private String name;
private String username;
private String password;
private String email;
#ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles;
}
UserDictionary
#Entity
#Data
#ToString(callSuper = true)
#EqualsAndHashCode(callSuper = true)
#AllArgsConstructor
#NoArgsConstructor
public class UserDictionary extends AbstractModelClass {
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "userDictionary")
private Set<WordSet> wordSets;
#OneToOne(cascade = CascadeType.ALL)
private User user;
#PrePersist
private void addDictionaryToWordSets() {
wordSets.forEach(wordSet -> wordSet.setUserDictionary(this));
}
}
WordSet
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#EqualsAndHashCode(callSuper = true, exclude = {"studiedWords", "userDictionary"})
#ToString(callSuper = true, exclude = {"studiedWords", "userDictionary"})
public class WordSet extends AbstractModelClass {
#NotBlank
private String name;
#NotBlank
private String description;
#ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private List<StudiedWord> studiedWords;
#ManyToOne(fetch = FetchType.EAGER)
private UserDictionary userDictionary;
public WordSet(String name, String description, List<StudiedWord> studiedWords) {
this.name = name;
this.description = description;
this.studiedWords = studiedWords;
}
public WordSet(Long id, String name, String description, List<StudiedWord> studiedWords) {
super(id);
this.name = name;
this.description = description;
this.studiedWords = studiedWords;
}
#PreRemove
private void removeFromUserDictionary() {
userDictionary.getWordSets().removeIf(this::equals);
}
}
Here is part of my WordSetDao:
#Override
public Optional<WordSet> findByIdAndUsername(long id, String username) {
return findOrEmpty(() -> entityManager.createQuery(
"SELECT w FROM WordSet w " +
"WHERE w.userDictionary.user.username = :username AND w.id = :id", WordSet.class)
.setParameter("id", id)
.setParameter("username", username)
.getSingleResult());
}
#Override
public void deleteByIdAndUsername(long id, String username) {
entityManager.createQuery(
"DELETE FROM WordSet w WHERE w.userDictionary.user.username = :username AND w.id = :id")
.setParameter("id", id)
.setParameter("username", username)
.executeUpdate();
}
findByIdAndUsername works fine, but delete throws following exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [/* delete FKs in join table */ delete from word_set_studied_words where (word_set_id) in (select id from word_set where username=? and id=?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:894)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:654)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at io.github.solomkinmv.glossary.web.security.auth.JwtTokenAuthenticationProcessingFilter.successfulAuthentication(JwtTokenAuthenticationProcessingFilter.java:58)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:240)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at io.github.solomkinmv.glossary.web.controller.WordSetControllerTest.deleteWordSet(WordSetControllerTest.java:236)
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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.restdocs.JUnitRestDocumentation$1.evaluate(JUnitRestDocumentation.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [/* delete FKs in join table */ delete from word_set_studied_words where (word_set_id) in (select id from word_set where username=? and id=?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
at io.github.solomkinmv.glossary.persistence.dao.impl.WordSetJpaDao$$EnhancerBySpringCGLIB$$48825a47.deleteByIdAndUsername(<generated>)
at io.github.solomkinmv.glossary.service.domain.impl.WordSetServiceImpl.deleteByIdAndUsername(WordSetServiceImpl.java:128)
at io.github.solomkinmv.glossary.service.domain.impl.WordSetServiceImpl$$FastClassBySpringCGLIB$$c3da160a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
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:282)
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:656)
at io.github.solomkinmv.glossary.service.domain.impl.WordSetServiceImpl$$EnhancerBySpringCGLIB$$4b4a0f55.deleteByIdAndUsername(<generated>)
at io.github.solomkinmv.glossary.web.controller.WordSetController.deleteWordSet(WordSetController.java:79)
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: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)
... 70 more
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:78)
at org.hibernate.hql.internal.ast.exec.BasicExecutor.doExecute(BasicExecutor.java:78)
at org.hibernate.hql.internal.ast.exec.DeleteExecutor.execute(DeleteExecutor.java:107)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:429)
at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:374)
at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1348)
at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:102)
at org.hibernate.jpa.internal.QueryImpl.internalExecuteUpdate(QueryImpl.java:405)
at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:61)
at io.github.solomkinmv.glossary.persistence.dao.impl.WordSetJpaDao.deleteByIdAndUsername(WordSetJpaDao.java:50)
at io.github.solomkinmv.glossary.persistence.dao.impl.WordSetJpaDao$$FastClassBySpringCGLIB$$3577673c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 98 more
Caused by: org.h2.jdbc.JdbcSQLException: Column "USERNAME" not found; SQL statement:
/* delete FKs in join table */ delete from word_set_studied_words where (word_set_id) in (select id from word_set where username=? and id=?) [42122-193]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:147)
at org.h2.expression.Comparison.optimize(Comparison.java:178)
at org.h2.expression.ConditionAndOr.optimize(ConditionAndOr.java:130)
at org.h2.command.dml.Select.prepare(Select.java:856)
at org.h2.engine.Session.optimizeQueryExpression(Session.java:233)
at org.h2.expression.ConditionInSelect.optimize(ConditionInSelect.java:117)
at org.h2.command.dml.Delete.prepare(Delete.java:131)
at org.h2.command.Parser.prepareCommand(Parser.java:259)
at org.h2.engine.Session.prepareLocal(Session.java:561)
at org.h2.engine.Session.prepareCommand(Session.java:502)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1203)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:73)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:287)
at sun.reflect.GeneratedMethodAccessor93.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
at com.sun.proxy.$Proxy87.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$1.doPrepare(StatementPreparerImpl.java:87)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
... 113 more
Also, instead of
DELETE FROM WordSet w WHERE w.userDictionary.user.username = :username AND w.id = :id
I've tried following query:
DELETE FROM WordSet w
WHERE w IN
(SELECT ws FROM UserDictionary u
JOIN u.wordSets ws
WHERE u.user.username = :username AND ws.id = :id)
And it works on my H2 database, but fails on MySQL with following exception:
java.sql.SQLException: You can't specify target table 'word_set' for update in FROM clause
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.40.jar!/:5.1.40]
...
I've googled about subqueries and MySQL (one, two), but couldn't find out how to make such trick with JPA.
So, how to delete wordset? Is there something wrong with my entity mapping?
Here is my DB schema, it looks correct:
There are some many things that are wrong in this mapping:
Using EAGER fetching for every collection type is even more of an issue than your current problem. You are practically fetching the whole DB with any given query. Switching to FetchType.LAZY is better.
You said it works for H2, but that's not true:
Caused by: org.h2.jdbc.JdbcSQLException: Column "USERNAME" not found; SQL statement:
/* delete FKs in join table */ delete from word_set_studied_words where (word_set_id) in (select id from word_set where username=? and id=?) [42122-193]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
This type of query is not supported by MySQL:
DELETE FROM WordSet w
WHERE w IN
(SELECT ws FROM UserDictionary u
JOIN u.wordSets ws
WHERE u.user.username = :username AND ws.id = :id)
Joins are prohibited in bulk statements as explained in the Hibernate User Guide.
Now, depending on the number of entries you want to delete, a batch delete might be a better approach since you can prevent lost update anomaly.
You have a graph of interconnected entities here, so bulk delete might not help you anyway because you can't delete a parent record without deleting the child associations first.
Have you attempted a regular join in the delete? There is a similar question here:
Delete with Join in MySQL
...although not via JPA, but there is an accepted answer which shows and example of a join based delete, but it seems MySQL specific.
The trick is to specify the actual table in the delete clause itself, not just the from clause when you have other tables referenced via JOINs.
I'm not setup to test JPA against mysql at the moment. JQL might not be able to accommodate this, but you could probably do it with a native query.
java.sql.SQLException: You can't specify target table 'word_set' for
update in FROM clause
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.40.jar!/:5.1.40]
This exception is caused, because in MySQL you can not modify/delete the same table which you use in the SELECT part. Here documented this behaviour https://dev.mysql.com/doc/refman/5.6/en/update.html. The solutions 1) nesting the subquery deeper into a from clause or 2) join the table to itself
Getting java.sql.SQLException: Invalid column name even though column with same name are in table. what can be a reason?
I am trying to call sp with below code:
Session session = HibernateUtil.getSessionFactory().openSession();
Query query = session.getNamedQuery("EMPLOYEE.PRC_HB_EMP_SP1");
query.setParameter("IN_EMPID", empId);
List<Employee> empList = query.list();
System.out.println(empList);
Entity class Employee:
#Entity
#Table(name = "EMPLOYEE")
//#org.hibernate.annotations.NamedNativeQuery(name = "EMPLOYEE.PRC_HB_EMP_SP1", query = "call PRC_HB_EMP_SP1(?,:IN_EMPID)", callable = true, resultClass = Employee.class)
#org.hibernate.annotations.NamedNativeQuery(name = "EMPLOYEE.PRC_HB_EMP_SP1", query = "call PRC_HB_EMP_SP1(?,:IN_EMPID)", callable = true, resultClass = Employee.class)
public class Employee implements Serializable {
private static final long serialVersionUID = -723583058586873479L;
#Id
#Column(name = "EMPID")
private Integer empId;
#Column(name = "EMPNAME")
private String empName;
#Column(name = "ADDRESS")
private String empAddress;
#Column(name = "SALARY")
private Long salary;
#Column(name = "EMPAGE")
private Integer empAge;
............
}
here is sp:
create or replace PROCEDURE PRC_HB_EMP_SP1
(
Out_value OUT SYS_REFCURSOR,
IN_EMPID NUMBER
)
AS
BEGIN
open Out_value for
SELECT EMPID,EMPNAME
FROM EMPLOYEE
WHERE EMPID = IN_EMPID;
END PRC_HB_EMP_SP1;
Stacktrace:
SEVERE: Servlet.service() for servlet [sdnext] in context with path [/sdnext] threw exception [Request processing failed; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query] with root cause
java.sql.SQLException: Invalid column name
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:269)
at oracle.jdbc.driver.OracleStatement.get_column_index(OracleStatement.java:5971)
at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:1527)
at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:1482)
at org.hibernate.type.StringType.get(StringType.java:18)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:154)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:81)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2101)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1380)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1308)
at org.hibernate.loader.Loader.getRow(Loader.java:1206)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:580)
at org.hibernate.loader.Loader.doQuery(Loader.java:701)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2213)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:152)
at com.dineshonjava.controller.EmployeeController.getEmployeeDetail(EmployeeController.java:160)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
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:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Your mappings contain columns ADDRESS,SALARY and EMPAGE but those are missing from your SP.You need to include those in your statement.
I have a simple (I guess) problem but I have no idea what's wrong.
I'm trying to execute following HQL query:
String hql = "delete CinemaProgramme program where program.id in (select q.id from CinemaProgramme q left join q.timetable a " +
"where a > :today)";
and I get an error:
java.lang.UnsupportedOperationException: References to collections must be define a SQL alias
java.lang.UnsupportedOperationException: References to collections must be define a SQL alias
at org.hibernate.persister.collection.ElementPropertyMapping.toColumns(ElementPropertyMapping.java:69)
at org.hibernate.persister.collection.AbstractCollectionPersister.toColumns(AbstractCollectionPersister.java:1541)
at org.hibernate.hql.ast.tree.FromElement.getIdentityColumn(FromElement.java:348)
at org.hibernate.hql.ast.tree.IdentNode.resolveAsAlias(IdentNode.java:154)
at org.hibernate.hql.ast.tree.IdentNode.resolve(IdentNode.java:100)
at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:117)
at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:113)
at org.hibernate.hql.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:880)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:4834)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1326)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4471)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3992)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2047)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:831)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:617)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.collectionFunctionOrSubselect(HqlSqlBaseWalker.java:4696)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.inRhs(HqlSqlBaseWalker.java:4596)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4261)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2047)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:831)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.deleteStatement(HqlSqlBaseWalker.java:455)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:260)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
at movies.database.CinemaListDao.deleteOldData(CinemaListDao.java:97)
at movies.controller.MovieController.viewRegistration(MovieController.java:56)
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:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at movies.encoding.UTF8Filter.doFilter(UTF8Filter.java:14)
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)
However, when I just try to execute the query without the delete:
String hql = "from CinemaProgramme program where program.id in (select q.id from CinemaProgramme q left join q.timetable a " +
"where a > :today)";
Then it works fine....
Subquery itself also works correctly:
String hql = "select q.id from CinemaProgramme q left join q.timetable a " +
"where a > :today)"
........
#Entity
#Table(name = "cinema_programme")
public class CinemaProgramme implements Serializable {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#ElementCollection
#LazyCollection(LazyCollectionOption.FALSE)
#JoinColumn(name = "programme_id")
private List<Date> timetable;
#ManyToOne(cascade= CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "movie_id")
private Movie movie;
}
Any ideas?
PS.
delete from CinemaProgramme AS program - also doesn't work
There are not enough details about the entities. Does this work:
delete CinemaProgramme where id in (select q.id from CinemaProgramme q left join q.timetable a where a > :today)
OR
delete CinemaProgramme where timetable > :today