org.postgresql.util.PSQLException: ERROR: relation "sequence" does not exist - java

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.

Related

How to get specific columns from database using JPA in Spring Boot (Getting Exception while trying to fetch specific column from Database)?

I have one table and other child table connected with oneToMany relation. I want to get data from primary
table and secondary table on the basis of secondary table excluding other fields from primary table. I am trying to get data using JPA query with constructor to set fields in Bean and getting exception in console.
1.Entity Table:
#Entity
#Getter #Setter
#Accessors(chain = true)
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
#Table(name="entity")
#JsonInclude(value = Include.NON_NULL)
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="entityId")
public class EntityModel implements Serializable {
private static final long serialVersionUID = 8087473285130713445L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer entityId;
#Column(length = 100, nullable = false)
private String legalName;
//other fields
//.....
//....
#OneToMany(fetch=FetchType.LAZY,mappedBy = "entity")
private Set<EntityRoles> entityRoles;
public EntityModel(Integer entityId,String legalName,Set<EntityRoles> entityRoles){
this.entityId = entityId;
this.legalName = legalName;
this.entityRoles = entityRoles;
}
}
2.Entity Role Table:
#Getter #Setter
#Accessors(chain = true)
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "entity_roles")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="entityRolesId")
public class EntityRoles implements Serializable {
private static final long serialVersionUID = 4335089064220416028L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer entityRolesId;
#Column(length = 10, nullable = false)
private String roleName;
#ManyToOne
#JoinColumn(name = "entity_id", nullable = false)
private EntityModel entity;
public EntityRoles(Integer entityRolesId, String roleName) {
super();
this.entityRolesId = entityRolesId;
this.roleName = roleName;
}
}
3.Repository:
#Repository
public interface EntityRepo extends JpaRepository<EntityModel, Integer>{
#Query(value = "SELECT new EntityModel(e.entityId,e.legalName,e.entityRoles) FROM EntityModel AS e INNER JOIN e.entityRoles er WHERE er.roleName NOT IN('FINANCIER','HOST','BUYER')")
Page<EntityModel> findAllByAnchorSellerAndDealerEntity(Pageable page);
}
Exception (StackTrace):
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:281)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy153.findAllByAnchorSellerAndDealerEntity(Unknown Source)
at com.entpaynet.service.EntityService.getEntityByTypeWithPage(EntityService.java:253)
at com.entpaynet.service.EntityService$$FastClassBySpringCGLIB$$879e027e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:685)
at com.entpaynet.service.EntityService$$EnhancerBySpringCGLIB$$ad961a7f.getEntityByTypeWithPage(<generated>)
at com.entpaynet.controller.EntityController.getEntityByPage(EntityController.java:215)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
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.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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.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:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
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: 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:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2292)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2050)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2012)
at org.hibernate.loader.Loader.doQuery(Loader.java:953)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2815)
at org.hibernate.loader.Loader.doList(Loader.java:2797)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2629)
at org.hibernate.loader.Loader.list(Loader.java:2624)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:396)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1396)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1558)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1526)
at org.hibernate.query.Query.getResultList(Query.java:165)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:177)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:154)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:618)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 67 common frames omitted
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '. as col_14_0_ from entity entitymode0_ inner join entity_roles entityrole1_ on ' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57)
... 96 common frames omitted
Getting Exception due to following column :
#OneToMany(fetch=FetchType.LAZY,mappedBy = "entity")
private Set<EntityRoles> entityRoles;
How to get data in this case?
You are using new operator. This is for creating DTOs not querying entities. Your quers should look like:
#Query("SELECT e FROM EntityModel e INNER JOIN e.entityRoles er " +
"WHERE er.roleName NOT IN('FINANCIER','HOST','BUYER')")
Page<EntityModel> findAllByAnchorSellerAndDealerEntity(Pageable page);
}
Or if you want a DTO you have to create one that you have to use with the fully qualified classname
#Query("SELECT NEW packagename.EntityDTO(e.entityId,e.legalName,e.entityRoles) "+
"FROM EntityModel e INNER JOIN e.entityRoles er " +
"WHERE er.roleName NOT IN('FINANCIER','HOST','BUYER')")
Page<EntityDTO> findAllByAnchorSellerAndDealerEntity(Pageable page);
}

Could not locate appropriate constructor on class

I am trying to map my native SQL result to my POJO, but it's returning an error.
Here is the full stack trace:
Hibernate: SELECT * FROM members_tb where memberName like ?
2019-12-19 07:40:20.688 TRACE 32472 --- [nio-8084-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [%Frank%]
java.lang.IllegalArgumentException: Could not locate appropriate constructor on class : com.app.ecclesiamainframe.entity.Members
at org.hibernate.loader.custom.ConstructorResultColumnProcessor.resolveConstructor(ConstructorResultColumnProcessor.java:92)
at org.hibernate.loader.custom.ConstructorResultColumnProcessor.performDiscovery(ConstructorResultColumnProcessor.java:45)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:494)
at org.hibernate.loader.Loader.processResultSet(Loader.java:2338)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2294)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2050)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2012)
at org.hibernate.loader.Loader.doQuery(Loader.java:953)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2815)
at org.hibernate.loader.Loader.doList(Loader.java:2797)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2629)
at org.hibernate.loader.Loader.list(Loader.java:2624)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2123)
at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1134)
at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:173)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1526)
at org.hibernate.query.Query.getResultList(Query.java:165)
at com.app.ecclesiamainframe.service.impl.MembersServiceImpl.findByMembername(MembersServiceImpl.java:63)
at com.app.ecclesiamainframe.service.impl.MembersServiceImpl$$FastClassBySpringCGLIB$$b6791a90.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at com.app.ecclesiamainframe.service.impl.MembersServiceImpl$$EnhancerBySpringCGLIB$$81c0914a.findByMembername(<generated>)
at com.app.ecclesiamainframe.controller.MembersController.getMember(MembersController.java:64)
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:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
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.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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.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:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
2019-12-19 07:40:21.744 INFO 32472 --- [nio-8084-exec-2] i.StatisticalLoggingSessionEventListener : Session Metrics {
1250700 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
0 nanoseconds spent preparing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
0 nanoseconds spent performing 0 L2C puts;
0 nanoseconds spent performing 0 L2C hits;
0 nanoseconds spent performing 0 L2C misses;
0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
2019-12-19 08:39:48.231 WARN 32472 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=45s935ms542µs800ns).
2019-12-19 08:46:56.149 WARN 32472 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=3m17s562ms942µs).
2019-12-19 08:46:57.264 WARN 32472 --- [l-2 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-2 - Thread starvation or clock leap detected (housekeeper delta=3m17s563ms485µs800ns).
Here is my Membermapping.xml:
<sql-result-set-mapping name="MemberMappingXml">
<constructor-result target-class="com.app.ecclesiamainframe.entity.Members">
<column name="memberId" />
<column name="dcaRegno" />
<column name="address" />
<column name="age" />
<column name="areaId" />
<column name="birthday" />
<column name="cellId" />
<column name="dca" />
<column name="department" />
<column name="editor" />
<column name="firstTime" />
<column name="gender" />
<column name="maritalStatus" />
<column name="memberEmail" />
<column name="memberHomePhoneNum" />
<column name="memberMobileNum" />
<column name="memberName" />
<column name="note" />
<column name="secondTime" />
</constructor-result>
</sql-result-set-mapping>
Here is my Entity Class:
/**
*
*/
package com.app.ecclesiamainframe.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.ColumnResult;
import javax.persistence.ConstructorResult;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import com.vladmihalcea.hibernate.type.json.JsonStringType;
import lombok.Data;
/**
* #author Harry
*
*/
#Entity
#Table(name="members_tb")
#Data
#TypeDef(
name = "json",
typeClass = JsonStringType.class
)
#SqlResultSetMapping(
name = "MemberMapping",
classes = #ConstructorResult(
targetClass = Members.class,
columns = {
#ColumnResult(name = "memberId", type = Long.class),
#ColumnResult(name = "dcaRegno", type = Long.class),
#ColumnResult(name = "address"),
#ColumnResult(name = "age"),
#ColumnResult(name = "areaId", type = Long.class),
#ColumnResult(name = "birthday"),
#ColumnResult(name = "cellId", type = Long.class),
#ColumnResult(name = "dca"),
#ColumnResult(name = "department"),
#ColumnResult(name = "editor"),
#ColumnResult(name = "firstTime"),
#ColumnResult(name = "gender"),
#ColumnResult(name = "maritalStatus"),
#ColumnResult(name = "memberEmail"),
#ColumnResult(name = "memberHomePhoneNum", type = Long.class),
#ColumnResult(name = "memberMobileNum", type = Long.class),
#ColumnResult(name = "memberName"),
#ColumnResult(name = "note"),
#ColumnResult(name = "secondTime")
}))
public class Members implements Serializable {
/**
*
*/
public Members() {}
private static final long serialVersionUID = 1L;
#Id
#Column(name="memberId")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long memberId;
#Column(name="dcaRegno")
private Long dcaRegno;
#Column(name="memberName")
private String memberName;
#Column(name="memberMobileNum")
private Long memberMobileNum;
#Column(name="memberHomePhoneNum")
private Long memberHomePhoneNum;
#Column(name="memberEmail")
private String memberEmail;
#Column(name="gender")
private String gender;
#Column(name="department")
private String department;
#Type(type = "json")
#Column(columnDefinition = "json",name="address")
private String address;
#Column(name="cellId")
private Long cellId;
#Column(name="areaId")
private Long areaId;
#Column(name="maritalStatus")
private String maritalStatus;
#Column(name="age")
private String age;
#Column(name="birthday")
private String birthday;
#Column(name="firstTime")
private String firstTime;
#Column(name="secondTime")
private String secondTime;
#Type(type = "json")
#Column(columnDefinition = "json",name="dca")
private String dca;
#Column(name="note")
private String note;
#Column(name="editor")
private String editor;
public Members(Long memberId,String memberName) {
this.memberId = memberId;
this.memberName = memberName;
}
public Members(Long memberId,Long dcaRegno,String memberName,Long memberMobileNum,Long memberHomePhoneNum,String memberEmail,String gender,String department,
String address,Long cellId,Long areaId,String maritalStatus,String age,String birthday,String firstTime,String secondTime,
String dca,String note,String editor) {
this.memberId = memberId;
this.dcaRegno = dcaRegno;
this.address = address;
this.age = age;
this.areaId = areaId;
this.birthday = birthday;
this.cellId = cellId;
this.dca = dca;
this.department = department;
this.editor = editor;
this.firstTime = firstTime;
this.gender = gender;
this.maritalStatus = maritalStatus;
this.memberEmail = memberEmail;
this.memberHomePhoneNum = memberHomePhoneNum;
this.memberMobileNum = memberMobileNum;
this.memberName = memberName;
this.note = note;
this.secondTime = secondTime;
}
}
Here is my Member Service Implementation:
#Transactional
#SuppressWarnings("unchecked")
public List<Members> findByMembername(String memberName)
{
//return membersDao.findByMemberName(memberName);
List<Members> members = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
// Native query selecting all columns
Query query = session.createNativeQuery("SELECT * FROM members_tb where memberName like :memberName","MemberMapping")
.setParameter("memberName","%"+memberName+"%"); //named parameter binding
members = query.getResultList();
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
// HibernateUtil.shutdown();
return members;
}
Please how do i do away with the error and design an appropriate constructor ???
Possibly if i don't have to load every column into the constructor although i want all columns mapped in the result.
You will have to create a constructor for this.
Create a constructor in the class in which you have used SqlResultsetMapping and keep the variables in the constructor in the same sequence as you have kept them in the SqlResultsetMapping
The listed columns are not in the same order as the constructor parameters.
Parameters Columns
========================= ==================
Long memberId memberId
Long dcaRegno dcaRegno
String memberName address
Long memberMobileNum age
Long memberHomePhoneNum areaId
String memberEmail birthday
String gender cellId
String department dca
String address department
Long cellId editor
Long areaId firstTime
String maritalStatus gender
String age maritalStatus
String birthday memberEmail
String firstTime memberHomePhoneNum
String secondTime memberMobileNum
String dca memberName
String note note
String editor secondTime
please create this constructor in pojo class.As i can see mismatch between constructor
Members(Long memberId,Long dcaRegno,String address,String age,Long areaId,String birthday,Long cellId,String dca,String department,String editor,String firstTime,String gender,String maritalStatus,String memberEmail,Long memberHomePhoneNum,Long memberMobileNum,String memberName,String note,String secondTime)
hope this will work for you

Hibernate oneToMany SQLGrammarException

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

org.springframework.dao.InvalidDataAccessResourceUsageException while fetching data from multiple tables

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/iFKXQWXBTFiYWqY5qjhqlSsHYwWQatVErKJUClOybOe1RKZUUboocr0SWFJ6kB6radRHFRQyCZ7REpAlNy7BOqHotZhMoAGy6MGyGZ0Unckx7DxC15y8DgomJwA5KXiZKZlHFJrkfNMI5twLKvaSh1RYnMKKHqJTRgVBwX2ia4oRK5rXHBkwtXA9OUnAKjFHJU14USoFJwXB3V1hcMdQKq8lZLoW0pYYBoKLCNg5FllNKIWlpYW0rO4arELWZbWBCZiiKK3E4boqjGYexWvxNGQs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L9Xo77JJKu1FKM52gewPDmukOF7O3HkoTscHQ4m+x33HFJJMJXEawScegWpi2kb3HQoRxDefoUkkPajR8xnPxLefoV38Q3n6FJJRtRyysaa7efoVY0MYyBfhyKSSNh4Yjrnvir9xrMWwi7t54Hmo2KxTdtU+RSSR2Z8Y8gxmjYA4i3GPFFGJbBv6FJJAyRTQbakCFdnP5pJJIW0sf/9k=, fullName=null, userPassword=e7202d28c87440d38bd5bf4ff37c7fcc, 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.

Spring JPA, #JointTable annotation not working

What is wrong: I'm trying to implement login using Spring Security. I'm using Spring Security's default endpoint login. I keep receiving 500s and I believe it's due to incorrect joint because when I'm printing
public Set<Role> getRoles() {
System.out.println("roles");
System.out.println(roles);
return roles;
}
roles is null. 'll show my stack trace at the end of the question.
What I want to have: correct working join.
My code
Join:
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "userrole",
joinColumns = #JoinColumn(name = "iduser"),
inverseJoinColumns = #JoinColumn(name = "roleid"))
private Set<Role> roles;
Whole Users model:
#Entity
#Table(name = "user_1")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "iduser")
private Integer id;
#Column(name="id_points")
private Integer idPoints;
#Column(name="username")
private String userName;
#Column(name="isblocked")
private Boolean isBlocked;
#Column(name="email")
private String email;
#Column(name="lastname")
private String lastName;
#Column(name="firstname")
private String firstName;
#Column(name="password")
private String password;
#Column(name="token")
private String token;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "userrole",
joinColumns = #JoinColumn(name = "iduser"),
inverseJoinColumns = #JoinColumn(name = "roleid"))
private Set<Role> roles;
public Users() {
}
public Users(Users users) {
this.id = users.getId();
this.idPoints = users.getIdPoints();
this.userName = users.getUserName();
this.isBlocked = users.getBlocked();
this.email = users.getEmail();
this.lastName = users.getLastName();
this.firstName = users.getFirstName();
this.password = users.getPassword();
this.token = users.getToken();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getIdPoints() {
return idPoints;
}
public void setIdPoints(Integer idPoints) {
this.idPoints = idPoints;
}
public String getUserName() {
System.out.println(userName);
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Boolean getBlocked() {
return isBlocked;
}
public void setBlocked(Boolean blocked) {
isBlocked = blocked;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Set<Role> getRoles() {
System.out.println("roles");
System.out.println(roles);
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
CustomUsersDetails:
package com.shareabook.model;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.stream.Collectors;
public class CustomUserDetails extends Users implements UserDetails {
public CustomUserDetails(final Users users) {
super(users);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
.collect(Collectors.toList());
}
#Override
public String getPassword() {
return super.getPassword();
}
#Override
public String getUsername() {
return super.getUserName();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Role model
#Entity
#Table(name = "role")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "roleid")
private Integer role_id;
#Column(name = "role")
private String role;
public Role() {
}
public Integer getRole_id() {
return role_id;
}
public void setRole_id(Integer role_id) {
this.role_id = role_id;
}
public String getRole() {
System.out.println("role");
System.out.println(role);
return role;
}
public void setRole(String role) {
this.role = role;
}
}
How I create database:
CREATE TABLE Role (
roleId INTEGER NOT NULL,
role VARCHAR NOT NULL,
CONSTRAINT pkrole PRIMARY KEY (roleId)
);
CREATE SEQUENCE user_1_iduser_seq;
CREATE TABLE User_1 (
idUser INTEGER NOT NULL DEFAULT nextval('user_1_iduser_seq'),
id_points INTEGER NOT NULL,
userName VARCHAR NOT NULL,
isBlocked BOOLEAN DEFAULT False NOT NULL,
email VARCHAR NOT NULL,
lastName VARCHAR NOT NULL,
firstName VARCHAR NOT NULL,
password VARCHAR NOT NULL,
token VARCHAR,
CONSTRAINT pkuser PRIMARY KEY (idUser)
);
ALTER SEQUENCE user_1_iduser_seq OWNED BY User_1.idUser;
CREATE TABLE userRole (
idUser INTEGER NOT NULL,
roleId INTEGER NOT NULL
);
ALTER TABLE userRole ADD CONSTRAINT role_userrole_fk
FOREIGN KEY (roleId)
REFERENCES Role (roleId)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
ALTER TABLE User_1 ADD CONSTRAINT points_us_fk
FOREIGN KEY (id_points)
REFERENCES Points (idPoints)
ON DELETE CASCADE
ON UPDATE CASCADE
NOT DEFERRABLE;
ALTER TABLE userRole ADD CONSTRAINT user_1_userrole_fk
FOREIGN KEY (idUser)
REFERENCES User_1 (idUser)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
How I populate databse with data:
INSERT INTO Role VALUES(1, 'ADMIN');
INSERT INTO Role VALUES(2, 'USER');
INSERT INTO Publisher VALUES(1, 'Zielona Sowa');
INSERT INTO Category VALUES(1,'kryminal');
INSERT INTO Points VALUES(1,20);
INSERT INTO Author VALUES(1, 'Tolkien', 'John Ronald Reuel');
INSERT INTO User_1 VALUES(1,1,'oliwka',false,'oliwka#wp.pl','m','o','jakies');
INSERT INTO userRole VALUES(1,1);
INSERT INTO Book VALUES(1,1,1,'Hobbit',null,3,false,1937);
INSERT INTO BooksByAuthors VALUES(1,1,1);
INSERT INTO BooksByCategory VALUES(1,1,1);
Stack trace:
Hibernate: select users0_.iduser as iduser1_1_, users0_.email as email2_1_, users0_.firstname as firstnam3_1_, users0_.id_points as id_point4_1_, users0_.isblocked as isblocke5_1_, users0_.lastname as lastname6_1_, users0_.password as password7_1_, users0_.token as token8_1_, users0_.username as username9_1_ from user_1 users0_ where users0_.username=?
Hibernate: select roles0_.iduser as iduser1_2_0_, roles0_.roleid as roleid2_2_0_, role1_.roleid as roleid1_0_1_, role1_.role as role2_0_1_ from userrole roles0_ inner join role role1_ on roles0_.roleid=role1_.roleid where roles0_.iduser=?
oliwka
roles
null
2017-10-29 15:04:50.241 ERROR 11896 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.NullPointerException: null
at com.shareabook.model.CustomUserDetails.getAuthorities(CustomUserDetails.java:18) ~[classes/:na]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.createSuccessAuthentication(AbstractUserDetailsAuthenticationProvider.java:225) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:197) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_77]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_77]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_77]
The association between User and Role is Many-to-Many and not One-to-many.
Change your mappings like so in the User entity
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
joinColumns = #JoinColumn(name = "iduser"),
inverseJoinColumns = #JoinColumn(name = "roleid")
)
private Set<Role> roles;

Categories