I have a strange behaviour when updating entities (via entity views) in Quarkus native (it works fine on jvm). These are my entities:
#Entity
public class Role extends BaseEntity {
private boolean deleted;
private String name;
#OneToMany
private Set<LocalizedText> localizedDescriptions = new HashSet<>();
#ManyToMany
private Set<Permission> permissions = new HashSet<>();
//SETTERS AND GETTERS
}
#Entity
public class LocalizedText extends BaseEntity {
#NotBlank
private String language;
#NotBlank
private String text;
}
#Entity
public class Permission extends BaseEntity {
private boolean deleted;
#NotBlank
private String name;
#OneToMany
#NotEmpty
private Set<LocalizedText> localizedDescriptions = new HashSet<>();
}
And here's the entity views:
#EntityView(Role.class)
#CreatableEntityView
#UpdatableEntityView
public interface RoleUpdateView {
#IdMapping
Long getId();
String getName();
void setName(String name);
#UpdatableMapping
Set<LocalizedTextUpdateView> getLocalizedDescriptions();
#UpdatableMapping
Set<SimplePermissionUpdateView> getPermissions();
}
#EntityView(LocalizedText.class)
#CreatableEntityView
#UpdatableEntityView
public interface LocalizedTextUpdateView {
#IdMapping
Long getId();
String getLanguage();
void setLanguage(String language);
String getText();
void setText(String text);
}
#EntityView(Permission.class)
#CreatableEntityView
#UpdatableEntityView
public interface SimplePermissionUpdateView {
#IdMapping
Long getId();
}
As I said it works just fine when using the jvm, but it only works with entity creation in native mode. When updating an entity I get a NPE. Here's the trace:
org.jboss.resteasy.spi.UnhandledException: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.NullPointerException
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:106)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:372)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:218)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:519)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:138)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:84)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:41)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.StaticResourcesRecorder.lambda$start$1(StaticResourcesRecorder.java:65)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$4.handle(VertxHttpRecorder.java:338)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$4.handle(VertxHttpRecorder.java:316)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.security.HttpAuthorizer.doPermissionCheck(HttpAuthorizer.java:116)
at io.quarkus.vertx.http.runtime.security.HttpAuthorizer.checkPermission(HttpAuthorizer.java:99)
at io.quarkus.vertx.http.runtime.security.HttpSecurityRecorder$3.handle(HttpSecurityRecorder.java:218)
at io.quarkus.vertx.http.runtime.security.HttpSecurityRecorder$3.handle(HttpSecurityRecorder.java:210)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.security.HttpSecurityRecorder$2$2.onItem(HttpSecurityRecorder.java:143)
at io.quarkus.vertx.http.runtime.security.HttpSecurityRecorder$2$2.onItem(HttpSecurityRecorder.java:104)
at io.smallrye.mutiny.operators.uni.UniMemoizeOp.drain(UniMemoizeOp.java:152)
at io.smallrye.mutiny.operators.uni.UniMemoizeOp.onItem(UniMemoizeOp.java:172)
at io.smallrye.mutiny.operators.uni.UniOnItemTransformToUni$UniOnItemTransformToUniProcessor.onItem(UniOnItemTransformToUni.java:60)
at io.smallrye.mutiny.operators.uni.UniOnItemTransformToUni$UniOnItemTransformToUniProcessor.onItem(UniOnItemTransformToUni.java:60)
at io.smallrye.mutiny.operators.uni.builders.UniCreateFromKnownItem$KnownItemSubscription.forward(UniCreateFromKnownItem.java:38)
at io.smallrye.mutiny.operators.uni.builders.UniCreateFromKnownItem$KnownItemSubscription.access$100(UniCreateFromKnownItem.java:26)
at io.smallrye.mutiny.operators.uni.builders.UniCreateFromKnownItem.subscribe(UniCreateFromKnownItem.java:23)
at io.smallrye.mutiny.operators.AbstractUni.subscribe(AbstractUni.java:36)
at io.smallrye.mutiny.operators.uni.UniOnItemTransformToUni$UniOnItemTransformToUniProcessor.performInnerSubscription(UniOnItemTransformToUni.java:81)
at io.smallrye.mutiny.operators.uni.UniOnItemTransformToUni$UniOnItemTransformToUniProcessor.onItem(UniOnItemTransformToUni.java:57)
at io.smallrye.mutiny.operators.uni.builders.DefaultUniEmitter.complete(DefaultUniEmitter.java:36)
at io.quarkus.security.runtime.QuarkusIdentityProviderManagerImpl$1$1$1$1.run(QuarkusIdentityProviderManagerImpl.java:58)
at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2415)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
at java.lang.Thread.run(Thread.java:829)
at org.jboss.threads.JBossThread.run(JBossThread.java:501)
at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:553)
at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:192)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.NullPointerException
at com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.getQueryParamEntries(HibernateExtendedQuerySupport.java:824)
at com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.createQueryParameters(HibernateExtendedQuerySupport.java:719)
at com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.executeUpdate(HibernateExtendedQuerySupport.java:415)
at com.blazebit.persistence.impl.plan.CustomModificationQueryPlan.executeUpdate(CustomModificationQueryPlan.java:52)
at com.blazebit.persistence.impl.query.CustomSQLQuery.executeUpdate(CustomSQLQuery.java:60)
at com.blazebit.persistence.view.impl.update.flush.CollectionAttributeFlusher.addElements(CollectionAttributeFlusher.java:534)
at com.blazebit.persistence.view.impl.update.flush.CollectionAttributeFlusher.replaceCollection(CollectionAttributeFlusher.java:1025)
at com.blazebit.persistence.view.impl.update.flush.CollectionAttributeFlusher.replaceCollection(CollectionAttributeFlusher.java:64)
at com.blazebit.persistence.view.impl.update.flush.AbstractPluralAttributeFlusher.invokeFlushOperation(AbstractPluralAttributeFlusher.java:286)
at com.blazebit.persistence.view.impl.update.flush.CollectionAttributeFlusher.flushQuery(CollectionAttributeFlusher.java:287)
at com.blazebit.persistence.view.impl.update.flush.CollectionAttributeFlusher.flushQuery(CollectionAttributeFlusher.java:64)
at com.blazebit.persistence.view.impl.update.flush.CompositeAttributeFlusher.flushQuery(CompositeAttributeFlusher.java:450)
at com.blazebit.persistence.view.impl.update.EntityViewUpdaterImpl.update(EntityViewUpdaterImpl.java:711)
at com.blazebit.persistence.view.impl.update.EntityViewUpdaterImpl.executeUpdate(EntityViewUpdaterImpl.java:637)
at com.blazebit.persistence.view.impl.EntityViewManagerImpl.update(EntityViewManagerImpl.java:1182)
at com.blazebit.persistence.view.impl.EntityViewManagerImpl.update(EntityViewManagerImpl.java:1142)
at com.blazebit.persistence.view.impl.EntityViewManagerImpl.save(EntityViewManagerImpl.java:1059)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService.save(RolesService.java:95)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService_Subclass.save$$superaccessor8(RolesService_Subclass.zig:1366)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService_Subclass$$function$$8.apply(RolesService_Subclass$$function$$8.zig:33)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.security.runtime.interceptor.SecurityHandler.handle(SecurityHandler.java:24)
at io.quarkus.security.runtime.interceptor.RolesAllowedInterceptor.intercept(RolesAllowedInterceptor.java:29)
at io.quarkus.security.runtime.interceptor.RolesAllowedInterceptor_Bean.intercept(RolesAllowedInterceptor_Bean.zig:386)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:50)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInCallerTx(TransactionalInterceptorBase.java:252)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:34)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:53)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:26)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(TransactionalInterceptorRequired_Bean.zig:340)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService_Subclass.save(RolesService_Subclass.zig:1323)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService.update(RolesService.java:101)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService_Subclass.update$$superaccessor7(RolesService_Subclass.zig:1253)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService_Subclass$$function$$7.apply(RolesService_Subclass$$function$$7.zig:33)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.security.runtime.interceptor.SecurityHandler.handle(SecurityHandler.java:24)
at io.quarkus.security.runtime.interceptor.RolesAllowedInterceptor.intercept(RolesAllowedInterceptor.java:29)
at io.quarkus.security.runtime.interceptor.RolesAllowedInterceptor_Bean.intercept(RolesAllowedInterceptor_Bean.zig:386)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:50)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:127)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:100)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:32)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:53)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:26)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(TransactionalInterceptorRequired_Bean.zig:340)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService_Subclass.update(RolesService_Subclass.zig:1210)
at cloud.officinaedisanto.heritage.coreservice.services.RolesService_ClientProxy.update(RolesService_ClientProxy.zig:225)
at cloud.officinaedisanto.heritage.coreservice.api.backoffice.RolesBOResource.update(RolesBOResource.java:53)
at cloud.officinaedisanto.heritage.coreservice.api.backoffice.RolesBOResource_Subclass.update$$superaccessor1(RolesBOResource_Subclass.zig:361)
at cloud.officinaedisanto.heritage.coreservice.api.backoffice.RolesBOResource_Subclass$$function$$1.apply(RolesBOResource_Subclass$$function$$1.zig:33)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.security.runtime.interceptor.SecurityHandler.handle(SecurityHandler.java:24)
at io.quarkus.security.runtime.interceptor.AuthenticatedInterceptor.intercept(AuthenticatedInterceptor.java:29)
at io.quarkus.security.runtime.interceptor.AuthenticatedInterceptor_Bean.intercept(AuthenticatedInterceptor_Bean.zig:378)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at cloud.officinaedisanto.heritage.coreservice.api.backoffice.RolesBOResource_Subclass.update(RolesBOResource_Subclass.zig:318)
at java.lang.reflect.Method.invoke(Method.java:566)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:643)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:507)
at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:457)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:459)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:419)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:393)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:68)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492)
... 50 more
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.getField(HibernateExtendedQuerySupport.java:1296)
at com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.getQueryParamEntries(HibernateExtendedQuerySupport.java:821)
... 127 more
Caused by: java.lang.NullPointerException
at com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.getField(HibernateExtendedQuerySupport.java:1291)
... 128 more
Any ideas on how to fix this error? I'm doing something wrong?
Thanks
euks
Related
I am very new in Spring Data JPA and I have the following problem trying to insert a record into a database table (I am using MariaDB) in a Spring Boot application.
This is my database table named customer_order:
'id', 'bigint(20)', 'NO', 'PRI', NULL, 'auto_increment'
'name', 'varchar(255)', 'NO', '', NULL, ''
'address', 'varchar(255)', 'NO', '', NULL, ''
'product', 'varchar(255)', 'NO', '', NULL, ''
'order_date_time', 'datetime', 'NO', '', NULL, ''
'quantity', 'tinyint(4)', 'NO', '', NULL, ''
This table is mapped with the CustomerOrder model class in my application:
#Entity // This tells Hibernate to make a table out of this class
#Table(name = "customer_order")
public class CustomerOrder {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name = "name")
private String fullName;
private String address;
private String product;
#Column(name = "order_date_time")
private String orderDate;
private int quantity;
public CustomerOrder() {
super();
}
public CustomerOrder(String fullName, String address, String product, String orderDate, int quantity) {
super();
//this.id = id;
this.fullName = fullName;
this.address = address;
this.product = product;
this.orderDate = orderDate;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return "CustomerOrder [id=" + id + ", fullName=" + fullName + ", address=" + address + ", product=" + product
+ ", orderDate=" + orderDate + ", quantity=" + quantity + "]";
}
}
I have this Spring Data JPA repository interface:
public interface OrderRepository extends CrudRepository<CustomerOrder, Integer> {
}
This is used by this service class to perfrom the database interaction:
#Service
public class OrderServiceImpl implements OrderService {
#Autowired
OrderRepository orderRepository;
#Override
public List<CustomerOrder> getOrdersList() {
List<CustomerOrder> result = (List<CustomerOrder>) orderRepository.findAll();
return result;
}
#Override
public void insertOrder(CustomerOrder order) {
orderRepository.save(order);
}
}
Finnally I have this test class:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = { Application.class })
#WebAppConfiguration
#ActiveProfiles(profiles = { "no-liquibase" })
public class ExcelResourceIntegrationTest {
#Autowired
OrderServiceImpl orderService;
#Test
public void insertOrderServiceTest() {
CustomerOrder testOrder = new CustomerOrder("TEST1",
"Test Street 35 - New York - USA",
"TEST PRODUCT 1", "2020-03-24 12:10:00",
3);
orderService.insertOrder(testOrder);
}
#Test
public void getOrdersListServiceTest() {
List<CustomerOrder> ordersList = orderService.getOrdersList();
assertThat(ordersList).isNotEmpty();
}
}
The problem is that performing the previous insertOrderServiceTest() it enters into the called service method but when this line is executed:
orderRepository.save(order);
I obtain the following error message into the console:
2020-03-24 04:20:56.915 INFO 4843 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#24e7087a, org.springframework.security.web.context.SecurityContextPersistenceFilter#3a45308f, org.springframework.security.web.header.HeaderWriterFilter#731fae, org.springframework.security.web.authentication.logout.LogoutFilter#52bc6fcf, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#64b8eb96, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#789d8fd6, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#5bb3dee7, org.springframework.security.web.session.SessionManagementFilter#4ae6451d, org.springframework.security.web.access.ExceptionTranslationFilter#58ad0586, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#1e36baca]
2020-03-24 04:20:57.670 INFO 4843 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-24 04:20:58.368 INFO 4843 --- [ main] c.s.e.i.ExcelResourceIntegrationTest : Started ExcelResourceIntegrationTest in 8.519 seconds (JVM running for 11.638)
2020-03-24 04:21:07.638 WARN 4843 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1146, SQLState: 42S02
2020-03-24 04:21:07.642 ERROR 4843 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : (conn:63) Table 'db_test.hibernate_sequence' doesn't exist
Query is: select nextval(hibernate_sequence)
and this exception into the 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:178)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy106.save(Unknown Source)
at com.springboot.excelapi.service.OrderServiceImpl.insertOrder(OrderServiceImpl.java:27)
at com.springboot.excelapi.integration.ExcelResourceIntegrationTest.insertOrderServiceTest(ExcelResourceIntegrationTest.java:104)
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.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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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.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:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
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.id.enhanced.SequenceStructure$1.getNextValue(SequenceStructure.java:95)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:523)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:115)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:710)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:696)
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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314)
at com.sun.proxy.$Proxy100.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:554)
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.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:371)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:204)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:657)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:621)
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.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)
... 61 more
Caused by: java.sql.SQLSyntaxErrorException: (conn:63) Table 'db_test.hibernate_sequence' doesn't exist
Query is: select nextval(hibernate_sequence)
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:224)
at org.mariadb.jdbc.MariaDbClientPreparedStatement.executeInternal(MariaDbClientPreparedStatement.java:232)
at org.mariadb.jdbc.MariaDbClientPreparedStatement.executeQuery(MariaDbClientPreparedStatement.java:177)
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)
... 93 more
Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Table 'db_test.hibernate_sequence' doesn't exist
Query is: select nextval(hibernate_sequence)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readErrorPacket(AbstractQueryProtocol.java:1098)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readPacket(AbstractQueryProtocol.java:1030)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.getResult(AbstractQueryProtocol.java:985)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:161)
at org.mariadb.jdbc.MariaDbClientPreparedStatement.executeInternal(MariaDbClientPreparedStatement.java:223)
... 97 more
The reason is this property, it uses a sequence from table db_test.hibernate_sequence.
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
if you want to use MySQL incrementing id, please use
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
You can tweak Hibernate to create schema on startup in tests, if you need the sequence.
I am developing a web application in which there is a feature to generate the password. I am using Spring Boot + Hibernate + JPA. I am able to use built-in JPA query like findByUserMobileNumber etc. But when it is coming to update the password in the database I am getting the error.
Here is my entity class:
package gvr.OtpOnWeb.entity;
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="tbl_users")
public class Users
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PK_AI_unbUserID")
private int userID;
#Column(name= "svName")
private String userName;
#Column(name = "UQ_svMobileNo")
private String userMobileNumber;
#Column(name="svEmailID")
private String userEmailId;
#Column(name= "bActiveFlag")
private int active;
#Column(name="svPassword")
private String password;
public Users()
{
super();
}
public Users(int userID, String userName, String userMobileNumber, String userEmailId, int active,
String password)
{
super();
this.userID = userID;
this.userName = userName;
this.userMobileNumber = userMobileNumber;
this.userEmailId = userEmailId;
this.active = active;
this.password = password;
}
public Users(Users users)
{
this.active = users.getActive();
this.userEmailId = users.getUserEmailId();
this.userName = users.getUserName();
this.userMobileNumber = users.getUserMobileNumber();
this.password = users.getPassword();
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMobileNumber() {
return userMobileNumber;
}
public void setUserMobileNumber(String userMobileNumber) {
this.userMobileNumber = userMobileNumber;
}
public String getUserEmailId() {
return userEmailId;
}
public void setUserEmailId(String userEmailId) {
this.userEmailId = userEmailId;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Here is repository code:
#Repository
public interface UserRepository extends JpaRepository<Users, Integer>, CrudRepository<Users, Integer> {
Users findByuserMobileNumber(String mobileNumber);
Users findByuserMobileNumberAndPassword(String mobileNumber, String password);
#Modifying
#Query("update tbl_users u set u.svPassword = :password where u.UQ_svMobileNo = :mobilenumber")
void updateuserPassword(#Param("password") String password, #Param("mobilenumber") String mobilenumber);
}
Here is my controller code:
#RequestMapping(value = "GeneratePassword", method = RequestMethod.POST)
public ModelAndView generatePassword(#ModelAttribute(name="generatePasswordForm") Password passwordObj, Model model)
{
String mobileNumber = passwordObj.getMobileNumber();
String enteredPassword = passwordObj.getPassword();
String confirmPassword = passwordObj.getConfirmPassword();
ModelAndView modelAndView = new ModelAndView("GeneratePassword");
logger.info("Entered Mobile Number :"+ mobileNumber);
logger.info("Entered Password :"+ enteredPassword);
logger.info("Entered Confirmed Password :"+ confirmPassword);
userObj = userRepository.findByuserMobileNumber(mobileNumber);
if(userObj == null)
{
logger.info("USER DOES NOT EXIST");
modelAndView.addObject("messageFromServer", "Mobile Number Is Not Registered");
}
else
{
logger.info("VALIDATING PASSWORD");
boolean isEnteredPasswordValid = validationObj.validatePassword(enteredPassword);
logger.info("IS PASSWORD VALID :"+ isEnteredPasswordValid);
boolean isConfirmPasswordValid = validationObj.validatePassword(confirmPassword);
logger.info("IS CONFIRMED PASSWORD VALID :"+ isConfirmPasswordValid);
boolean arePasswordSame = validationObj.arePasswordSame(enteredPassword, confirmPassword);
logger.info("ARE BOTH THE PASSWORD SAME :"+ arePasswordSame);
if(isEnteredPasswordValid == false)
{
String messageToSend = "ENTER PASSWORD IN CORRECT FORMAT";
modelAndView.addObject("messageFromServer", messageToSend);
modelAndView.addObject("mobileNumber", mobileNumber);
return modelAndView;
}
if(isConfirmPasswordValid == false)
{
String messageToSend = "ENTER CONFIRM PASSWORD IN CORRECT FORMAT";
modelAndView.addObject("messageFromServer", messageToSend);
}
if(arePasswordSame == false)
{
String messageToSend = "PASSWORD MISMATCH ERROR";
modelAndView.addObject("messageFromServer", messageToSend);
modelAndView.addObject("mobileNumber", mobileNumber);
}
else
{
// DO FURTHE PROCESSING
// ENCRYPT PASSWORD
String md5ConfirmedPassword = PasswordHashing.cryptWithMD5(confirmPassword);
userRepository.updateuserPassword(md5ConfirmedPassword, mobileNumber);
}
}
return modelAndView;
}
Whenever I start my application I get the following list of errors:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainController' defined in file [D:\Development\Eclipse Worspaces\otp_on_web\OtpOnWeb\target\classes\gvr\OtpOnWeb\controller\MainController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract void gvr.OtpOnWeb.repository.UserRepository.updateuserPassword(java.lang.String,java.lang.String)!
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1267)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1124)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:330)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
at gvr.OtpOnWeb.OtpOnWebApplication.main(OtpOnWebApplication.java:12)
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.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract void gvr.OtpOnWeb.repository.UserRepository.updateuserPassword(java.lang.String,java.lang.String)!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724)
... 24 more
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract void gvr.OtpOnWeb.repository.UserRepository.updateuserPassword(java.lang.String,java.lang.String)!
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:63)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:139)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:546)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.collect(Unknown Source)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:548)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:538)
at java.util.Optional.map(Unknown Source)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:538)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:317)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:286)
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141)
at org.springframework.data.util.Lazy.get(Lazy.java:63)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:289)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695)
... 35 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: tbl_users is not mapped [update tbl_users u set u.svPassword = :password where u.UQ_svMobileNo = :mobilenumber]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
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.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
at com.sun.proxy.$Proxy100.createQuery(Unknown Source)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
... 64 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: tbl_users is not mapped [update tbl_users u set u.svPassword = :password where u.UQ_svMobileNo = :mobilenumber]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:217)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
... 72 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: tbl_users is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:326)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3595)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.updateStatement(HqlSqlBaseWalker.java:377)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:269)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
... 78 more
What could be the probable error for this?
It should be like this :
#Query("update Users u set u.password = :password where u.userMobileNumber = :mobilenumber")
This is the error shown:
exception
<openjpa-2.3.0-r422266:1540826 fatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while processing registered class "class no.avexis.fjellkam.Models.Cabin".
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1684)
org.apache.openjpa.meta.ClassMetaData.getPCSubclasses(ClassMetaData.java:376)
org.apache.openjpa.jdbc.meta.MappingRepository.findBaseClassMapping(MappingRepository.java:1539)
org.apache.openjpa.jdbc.meta.MappingRepository.prepareMapping(MappingRepository.java:402)
org.apache.openjpa.meta.MetaDataRepository.preMapping(MetaDataRepository.java:769)
org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:658)
org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:418)
org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
org.apache.openjpa.enhance.ManagedClassSubclasser.configureMetaData(ManagedClassSubclasser.java:227)
org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:182)
org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:312)
org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:236)
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:212)
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
no.avexis.fjellkam.DAO.AdminDAO.getEvents(AdminDAO.java:161)
no.avexis.fjellkam.Controllers.Common.ArticleServlet.doGet(ArticleServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Can't overwrite cause with java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [org.apache.openjpa.util.IntId]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.Throwable.initCause(Throwable.java:457)
org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1324)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1203)
java.lang.ClassLoader.loadClass(ClassLoader.java:411)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
org.apache.openjpa.enhance.no$avexis$fjellkam$Models$Cabin$pcsubclass.pcNewObjectIdInstance(Unknown Source)
org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:140)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1731)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1681)
org.apache.openjpa.meta.ClassMetaData.getPCSubclasses(ClassMetaData.java:376)
org.apache.openjpa.jdbc.meta.MappingRepository.findBaseClassMapping(MappingRepository.java:1539)
org.apache.openjpa.jdbc.meta.MappingRepository.prepareMapping(MappingRepository.java:402)
org.apache.openjpa.meta.MetaDataRepository.preMapping(MetaDataRepository.java:769)
org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:658)
org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:418)
org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
org.apache.openjpa.enhance.ManagedClassSubclasser.configureMetaData(ManagedClassSubclasser.java:227)
org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:182)
org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:312)
org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:236)
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:212)
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
no.avexis.fjellkam.DAO.AdminDAO.getEvents(AdminDAO.java:161)
no.avexis.fjellkam.Controllers.Common.ArticleServlet.doGet(ArticleServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.ClassNotFoundException
org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1323)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1203)
java.lang.ClassLoader.loadClass(ClassLoader.java:411)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
org.apache.openjpa.enhance.no$avexis$fjellkam$Models$Cabin$pcsubclass.pcNewObjectIdInstance(Unknown Source)
org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:140)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1731)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1681)
org.apache.openjpa.meta.ClassMetaData.getPCSubclasses(ClassMetaData.java:376)
org.apache.openjpa.jdbc.meta.MappingRepository.findBaseClassMapping(MappingRepository.java:1539)
org.apache.openjpa.jdbc.meta.MappingRepository.prepareMapping(MappingRepository.java:402)
org.apache.openjpa.meta.MetaDataRepository.preMapping(MetaDataRepository.java:769)
org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:658)
org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:418)
org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
org.apache.openjpa.enhance.ManagedClassSubclasser.configureMetaData(ManagedClassSubclasser.java:227)
org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:182)
org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:312)
org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:236)
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:212)
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
no.avexis.fjellkam.DAO.AdminDAO.getEvents(AdminDAO.java:161)
no.avexis.fjellkam.Controllers.Common.ArticleServlet.doGet(ArticleServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Here is how I have class file looks like:
package no.avexis.fjellkam.Models;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "CABIN")
public class Cabin implements Serializable {
private static final long serialVersionUID = -9160490433220569097L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer cabinID;
private String cabin;
private String title;
private String description;
public Cabin() {
this.cabin = "";
this.title = "";
this.description = "";
}
public Cabin(String cabin, String title, String description) {
this.cabin = cabin;
this.title = title;
this.description = description;
}
public String getCabin() {
return cabin;
}
public void setCabin(String cabin) {
this.cabin = cabin;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCabinID() {
return cabinID;
}
}
I keep getting this error for all my classes, and I either must be overlooking something, or I've done something very wrong.
It would seem as though there is an error while parsing the class, or locating the class?
I can't figure out why validation errors raise instead of beign just displayed after submitting a form ? I'm using HIbernate, Spring and JSF. I declared validation as of JSR 303 and use Hibernate annotation as follows:
#Entity
#Table(name = "posts")
public class Post implements Serializable {
#Column(name = "title")
#NotEmpty(message = "Title should not be empty")
private String title;
... other fields are ommited
}
In the corresponding bean I'm trying to save a post as follows:
#Component
#ManagedBean
#RequestScoped
#URLMappings(mappings = {
#URLMapping(id = "posts", pattern = "/posts/", viewId = "/faces/posts/list.xhtml"),
#URLMapping(id = "new", pattern = "/posts/new", viewId = "/faces/posts/new.xhtml")
})
public class PostBean {
#Autowired
private PostService postService;
private List<Post> posts;
private Post post = new Post();
public List<Post> getPosts() {
return postService.findAll();
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
public String create(Post post) {
postService.save(post);
return "pretty:posts";
}
....
}
The Post related repository is declared as follows:
public interface PostRepository extends CrudRepository<Post, Long> {
public Post findByTitleIgnoreCase(String title);
}
When submitting a form I get the below error:
Caused by: javax.faces.el.EvaluationException: javax.validation.ConstraintViolationException: Validation failed for classes [com.airial.domain.Post] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='Title should not be empty', propertyPath=title, rootBeanClass=class com.airial.domain.Post, messageTemplate='Title should not be empty'}
]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 39 more
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [com.airial.domain.Post] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='Title should not be empty', propertyPath=title, rootBeanClass=class com.airial.domain.Post, messageTemplate='Title should not be empty'}
]
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:161)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:94)
at org.hibernate.action.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:160)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:65)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:179)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:672)
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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
Any idea on how to fix it, i.e. to run validation before save ?
You can find the projet at github repo: https://github.com/Javix/blog-jsf.
Thank you
I'm the following error when calling purchaseService.updatePurchase(purchase) inside my TagController:
SEVERE: Servlet.service() for servlet [PurchaseAPIServer] in context with path [/PurchaseAPIServer] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
at org.hibernate.collection.PersistentSet.add(PersistentSet.java:212)
at com.app.model.Purchase.addTags(Purchase.java:207)
at com.app.controller.TagController.createAll(TagController.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
TagController:
#RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags")
#ResponseStatus(HttpStatus.CREATED)
public void createAll(#PathVariable("purchaseId") final Long purchaseId, #RequestBody final Tag[] entities)
{
Purchase purchase = purchaseService.getById(purchaseId);
Set<Tag> tags = new HashSet<Tag>(Arrays.asList(entities));
purchase.addTags(tags);
purchaseService.updatePurchase(purchase);
}
Purchase:
#Entity
#XmlRootElement
public class Purchase implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 6603477834338392140L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(mappedBy = "purchase", fetch = FetchType.LAZY, cascade={CascadeType.ALL})
private Set<Tag> tags;
#JsonIgnore
public Set<Tag> getTags()
{
if (tags == null)
{
tags = new LinkedHashSet<Tag>();
}
return tags;
}
public void setTags(Set<Tag> tags)
{
this.tags = tags;
}
public void addTag(Tag tag)
{
tag.setPurchase(this);
this.tags.add(tag);
}
public void addTags(Set<Tag> tags)
{
Iterator<Tag> it = tags.iterator();
while (it.hasNext())
{
Tag tag = it.next();
tag.setPurchase(this);
this.tags.add(tag);
}
}
...
}
Tag:
#Entity
#XmlRootElement
public class Tag implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 5165922776051697002L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({#JoinColumn(name = "PURCHASEID", referencedColumnName = "ID")})
private Purchase purchase;
#JsonIgnore
public Purchase getPurchase()
{
return purchase;
}
public void setPurchase(Purchase purchase)
{
this.purchase = purchase;
}
}
PurchaseService:
#Service
public class PurchaseService implements IPurchaseService
{
#Autowired
private IPurchaseDAO purchaseDAO;
public PurchaseService()
{
}
#Transactional
public List<Purchase> getAll()
{
return purchaseDAO.findAll();
}
#Transactional
public Purchase getById(Long id)
{
return purchaseDAO.findOne(id);
}
#Transactional
public void addPurchase(Purchase purchase)
{
purchaseDAO.save(purchase);
}
#Transactional
public void updatePurchase(Purchase purchase)
{
purchaseDAO.update(purchase);
}
}
TagService:
#Service
public class TagService implements ITagService
{
#Autowired
private ITagDAO tagDAO;
public TagService()
{
}
#Transactional
public List<Tag> getAll()
{
return tagDAO.findAll();
}
#Transactional
public Tag getById(Long id)
{
return tagDAO.findOne(id);
}
#Transactional
public void addTag(Tag tag)
{
tagDAO.save(tag);
}
#Transactional
public void updateTag(Tag tag)
{
tagDAO.update(tag);
}
}
Any ideas on how I can fix this? (I want to avoid using EAGER loading).
Do I need to setup some form of session management for transactions?
Thanks
Updates based on JB suggestions
TagController
#RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags")
#ResponseStatus(HttpStatus.CREATED)
public void createAll(#PathVariable("purchaseId") final Long purchaseId, #RequestBody final Tag[] entities)
{
Purchase purchase = purchaseService.getById(purchaseId);
// Validation
RestPreconditions.checkRequestElementNotNull(purchase);
RestPreconditions.checkRequestElementIsNumeric(purchaseId);
Set<Tag> tags = new HashSet<Tag>(Arrays.asList(entities));
purchaseService.addTagsToPurchase(purchaseId, tags);
}
PurchaseService
#Transactional
public void addTagsToPurchase(Long purchaseId, Set<Tag> tags)
{
Purchase p = purchaseDAO.findOne(purchaseId);
p.addTags(tags);
}
You load the Purchase without initializing its tags collection and then, in your controller, once the transaction is committed and the session closed, you're adding a tag to this non-initialized collection. So obviously, this exception is thrown.
You have two possibilities:
Load the tags with the Purchase, either by calling Hibernate.initialize(purchase.getTags()), or by executing a JPQL query that loads the tag along with its tags, in a single query (select distinct p from Purchase p left join fetch p.tags).
Instead of having a service class that offers noting more than the DAO, add a real service method addTagsToPurchase(Long purchaseId, Set<Tag> tags) which reloads the purchase and adds the tags to this purchase. This is in fact the service method needed by your controller.
I of course prefer the second solution by far:
it shows why a service layer is useful,
it removes business code from the presentation layer to put it in the service layer,
it's more efficient
it's safer because it uses attached entities, and thus avoids the kind of exception you're having.
In general, if your controller, to execute a single atomic action, needs several calls to the service layer, it means that the service layer doesn't offer the needed functionality, and that the service is implemented in the presentation layer instead.