Error on CrudRepository. Whitelabel Error Page - spring-boot

I have an error that I cannot resolve in Spring boot 2.2.2 with my repository. This is a simple CRUD application using spring boot 2 with JPA MySQL and Web-Starter.
The error is:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Dec 16 10:03:20 GMT+01:00 2019
There was an unexpected error (type=Internal Server Error, status=500).
Invoked method public abstract java.lang.Iterable org.springframework.data.repository.CrudRepository.findAll() is no accessor method!
java.lang.IllegalArgumentException: Invoked method public abstract java.lang.Iterable org.springframework.data.repository.CrudRepository.findAll() is no accessor method!
at org.springframework.data.projection.Accessor.<init>(Accessor.java:50)
at org.springframework.data.projection.MapAccessingMethodInterceptor.invoke(MapAccessingMethodInterceptor.java:55)
at org.springframework.data.projection.ProjectingMethodInterceptor.invoke(ProjectingMethodInterceptor.java:65)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.ProxyProjectionFactory$TargetAwareMethodInterceptor.invoke(ProxyProjectionFactory.java:245)
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.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy133.findAll(Unknown Source)
at com.beroots.weblab2.controllers.TodoController.tplTodos(TodoController.java:32)
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.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.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:830)
My repository :
package com.beroots.weblab2.dao;
import java.sql.Date;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.beroots.weblab2.entities.Todo;
public interface TodoRepository extends CrudRepository<Todo, Long> {
List<Todo> findByName(String name);
List<Todo> findByCategory(String category);
List<Todo> findByDescription(String description);
List<Todo> findByDueDate(Date dueDate);
List<Todo> findByCreateDate(Date createDate);
List<Todo> findByState(boolean state);
}
And my controller:
package com.beroots.weblab2.controllers;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.beroots.weblab2.controllers.exceptions.HashGenerationException;
import com.beroots.weblab2.dao.TodoRepository;
import com.beroots.weblab2.entities.Todo;
#Controller
public class TodoController {
#Autowired
MessageSource messageSource;
#Autowired
private TodoRepository todoRepository;
// --------------------------------------
#RequestMapping(value = "/todos", method = RequestMethod.GET)
public String tplTodos(Model model, TodoRepository todoRepository) {
Iterable<Todo> todos = todoRepository.findAll();
model.addAttribute("todos", todos);
return "v-todo-index";
}
}
I do not understand why this error. My code seems correct ...
If someone has an idea ;)
Thank you in advance.

Annotate your TodoRepository with #Repository and remove TodoRepository from the method parameter.
#RequestMapping(value = "/todos", method = RequestMethod.GET)
public String tplTodos(Model model) {
Iterable<Todo> todos = todoRepository.findAll();
model.addAttribute("todos", todos);
return "v-todo-index";
}
#Repository
public interface TodoRepository extends CrudRepository<Todo, Long> {
List<Todo> findByName(String name);
List<Todo> findByCategory(String category);
List<Todo> findByDescription(String description);
List<Todo> findByDueDate(Date dueDate);
List<Todo> findByCreateDate(Date createDate);
List<Todo> findByState(boolean state);
}

First think first:
How about you try constructor based injection. Since that is the preferred way of injecting anyway.
private MessageSource messageSource;
private TodoRepository todoRepository
#Autowired
public TodoController(MessageSource messageSource, TodoRepository todoRepository) {
this.messageSource = messageSource;
this.todoRepository = todoRepository;
}
Second:
Why don't you add to your repo:
List<Todo> findAll();

Related

spring boot jasypt encrypts but not able to decrypt, throws EncryptionOperationNotPossibleException

I am using spring boot jasypt 3.0.3, jasypt-1.9.3 cli.
encryption
encrypt.bat input="shri" password=U0RELU1USS1Db3Vwb24tU2VydmljZQ== algorithm=PBEWITHMD5ANDDES saltGeneratorClassName=org.jasypt.salt.RandomSaltGenerator providerName=SunJCE ivGeneratorClassName=org.jasypt.iv.NoIvGenerator stringOutputType=base64
decryption
decrypt.bat input="MStQnSmJV13y7DAfL+7/JA==" password=U0RELU1USS1Db3Vwb24tU2VydmljZQ== algorithm=PBEWITHMD5ANDDES saltGeneratorClassName=org.jasypt.salt.RandomSaltGenerator providerName=SunJCE ivGeneratorClassName=org.jasypt.iv.NoIvGenerator stringOutputType=base64
Spring boot API
package com.example.demo;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
#SpringBootApplication
#EnableEncryptableProperties
public class DemoApplication {
private static final String SECRET_KEY = "U0RELU1USS1Db3Vwb24tU2VydmljZQ==";
private static final String ALGORITHM = "PBEWITHMD5ANDDES";
private static final String ITERATION = "1000";
private static final String POOL_SIZE = "1";
private static final String PROVIDER_NAME = "SunJCE";
private static final String SALT_CLASS = "org.jasypt.salt.RandomSaltGenerator";
private static final String IV = "org.jasypt.iv.NoIvGenerator";
private static final String OUTPUT_TYPE = "base64";
#Bean
#Primary
public static StringEncryptor jasyptStringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(SECRET_KEY);
config.setAlgorithm(ALGORITHM);
config.setKeyObtentionIterations(ITERATION);
config.setPoolSize(POOL_SIZE);
config.setProviderName(PROVIDER_NAME);
config.setSaltGeneratorClassName(SALT_CLASS);
config.setIvGeneratorClassName(IV);
config.setStringOutputType(OUTPUT_TYPE);
encryptor.setConfig(config);
return encryptor;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
controller
package com.example.demo.controller;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/jasypt")
class SpringBootController {
#Autowired
StringEncryptor stringEncryptor;
#Value("${my.secret}")
private String pass;
//working
#RequestMapping(value = "/viewPass")
public String viewPass() {
return pass;
}
//working
#GetMapping(value = "/jasyptEncode")
public String jasyptEncode(#RequestParam String plainText) {
System.out.println("jasyptEncode receives request parameters as ===" + plainText);
String newpass = stringEncryptor.encrypt(plainText);
return newpass;
}
//not working
#PostMapping(value = "/jasyptDecode")
public String jasyptDecode(#RequestBody String param) {
System.out.println("param = " + param);
String realpass = stringEncryptor.decrypt(param);
System.out.println(realpass);
return realpass ;
}
}
applications. properties - using CLI generated encrypted password
my.secret=ENC(MStQnSmJV13y7DAfL+7/JA==)
build .gradle
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id "io.freefair.lombok" version "6.1.0-m3"
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '16'
repositories {
mavenCentral()
}
dependencies {
implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.3'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
I am able to decrypt applications.properties password which is generated by CLI using spring boot API but at the time of passing the same password and decryption using API, it's saying EncryptionOperationNotPossibleException.
logs
2021-07-31 22:09:36.079 DEBUG 16072 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Failed to complete request: org.jasypt.exceptions.EncryptionOperationNotPossibleException
2021-07-31 22:09:36.201 ERROR 16072 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.jasypt.exceptions.EncryptionOperationNotPossibleException] with root cause
org.jasypt.exceptions.EncryptionOperationNotPossibleException: null
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.decrypt(StandardPBEByteEncryptor.java:1169) ~[jasypt-1.9.3.jar:na]
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.decrypt(StandardPBEStringEncryptor.java:738) ~[jasypt-1.9.3.jar:na]
at org.jasypt.encryption.pbe.PooledPBEStringEncryptor.decrypt(PooledPBEStringEncryptor.java:511) ~[jasypt-1.9.3.jar:na]
at com.example.demo.controller.SpringBootController.jasyptDecode(PrintPassInYmlController.java:34) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.9.jar:5.3.9]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1064) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.9.jar:5.3.9]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.50.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.9.jar:5.3.9]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.50.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.50.jar:9.0.50]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.9.jar:5.3.9]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.9.jar:5.3.9]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.9.jar:5.3.9]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
at java.base/java.lang.Thread.run(Thread.java:831) ~[na:na]
what ab am I missing?
got it
for anyone facing the same issue.
I was sending the password in query param and hence was getting alteredd.
took it in a class and it worked.
package com.example.demo.controller;
import lombok.Data;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
#RestController
#RequestMapping("/jasypt")
class SpringBootController {
#Autowired
StringEncryptor stringEncryptor;
#Value("${my.secret}")
private String pass;
#RequestMapping(value = "/viewPass")
public String viewPass() {
return pass;
}
#GetMapping(value = "/jasyptEncode")
public String jasyptEncode(#RequestParam String plainText) {
System.out.println("jasyptEncode receives request parameters as ===" + plainText);
String newpass = stringEncryptor.encrypt(plainText);
return newpass;
}
#PostMapping(value = "/jasyptDecode")
public String jasyptDecode(#RequestBody Temp temp) {
System.out.println("param = " + temp.getPass());
String realpass = stringEncryptor.decrypt(temp.getPass());
System.out.println(realpass);
return realpass;
}
}
#Data
class Temp implements Serializable {
private String pass;
}

How to create a specification for dates in JPA to find the greater/less etc?

I have a Maria database with a table with a column named registrated what is a TIMESTAMP. I would like to make specifications to find records that are before/after a date. I have this:
public class GreaterThanDate implements Specification<User> {
private transient SearchCriteria criteria;
public GreaterThanDate(SearchCriteria searchCriteria) {
criteria = searchCriteria;
}
#Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
return builder.greaterThanOrEqualTo(root.<Date>get(criteria.getKey()), formatter.parse(criteria.getValue().toString()));
} catch (ParseException e) {
System.out.println(e.getMessage());
}
}
}
public class SearchCriteria {
private String key;
private Object value;
}
This is a date that is found in my database: 2020-09-01 08:00:00.000000. If I try to find the records I get a java.lang.IllegalArgumentException. This is how I call it:
SearchCriteria criteria = new SearchCriteria("registered", "2020-09-01 08:00:00.000000");
GreaterThanDate specification = new GreaterThanDate(criteria);
userRepository.findAll(specification, pageable);
#Entity
public class User {
private ZonedDateTime registered;
}
Exception is java.lang.IllegalArgumentException: Invalid filter
parameters. 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:190)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
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:626) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) 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.AbstractRequestLoggingFilter.doFilterInternal(AbstractRequestLoggingFilter.java:289)
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.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: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:541)
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:373)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
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)
There are couple of problems with your code.
You entity class has java.time.ZonedDateTime type for the field. But you are trying to parse using SimpleDateFormat which is designed for old java.util.Date. Please use DateTimeFormatter to parse ZonedDateTime
private ZonedDateTime registered;
The date format yyyy-MM-dd'T'HH:mm:ss.SSSXXX doesn't match with the input date 2020-09-01 08:00:00.000000 so you cannot use this format to parse the date. You will get ParseException
Do not bury the exception. The exception that you posted on question might have been raised due to a different error.
} catch (ParseException e) {
System.out.println(e.getMessage());
}
See this working example and do the similar to fix your problem:
package stackoverflowdatespec
import lombok.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.stereotype.Component;
import javax.persistence.*;
import javax.persistence.criteria.*;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
#SpringBootApplication
public class StackOverFlowDateSpecApp {
public static void main(String[] args) {
SpringApplication.run(StackOverFlowDateSpecApp.class, args);
}
}
#Entity
#Data
#ToString
class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
private ZonedDateTime registered = ZonedDateTime.now();
}
interface ARepo extends JpaRepositoryImplementation<A, Long> {
}
#Component
#RequiredArgsConstructor
class Init {
final ARepo repo;
#EventListener
public void init(ContextRefreshedEvent evt) {
repo.save(new A());
System.out.println(repo.findAll());
SearchCriteria criteria = new SearchCriteria("registered", "2011-12-03T10:15:30+01:00");
System.out.println(repo.findAll(new GreaterThanDate(criteria), Pageable.unpaged()).getContent());
}
}
#RequiredArgsConstructor
class GreaterThanDate implements Specification<A> {
private final SearchCriteria criteria;
#Override
public Predicate toPredicate(Root<A> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
ZonedDateTime before = ZonedDateTime.parse(criteria.getValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"));
return builder.greaterThanOrEqualTo(root.get(criteria.getKey()), before);
}
}
#Data
#AllArgsConstructor
class SearchCriteria {
private String key;
private String value;
}

PDF File Size 0 byte and getting error in console

I'm getting error when i trying to generate pdf. I've used itext pdf for creating pdf. I got following error in sts3 console.
Error:
com.itextpdf.text.DocumentException: java.lang.NullPointerException
at com.itextpdf.text.pdf.PdfDocument.add(PdfDocument.java:821)
at com.itextpdf.text.Document.add(Document.java:277)
at com.doller.flightreservation.util.PDFGenerator.generateItinerary(PDFGenerator.java:28)
at com.doller.flightreservation.services.ReservationServiceImpl.bookFlight(ReservationServiceImpl.java:59)
at com.doller.flightreservation.controllers.ReservationController.completeReservation(ReservationController.java:37)
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:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
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.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:541)
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:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)
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: java.lang.NullPointerException
at com.itextpdf.text.pdf.PdfDocument.add(PdfDocument.java:438)
And my PDF file saved with 0 byte with proper name. But I'm getting different named file Itiniarary.pdf with blank file and file not opening.
I've share my code below:
PDFGenerator.java
package com.doller.flightreservation.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.springframework.stereotype.Component;
import com.doller.flightreservation.entities.Reservation;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
#Component
public class PDFGenerator {
public void generateItinerary(Reservation reservation, String filePath) {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
document.add(generateTable(reservation));
document.close();
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
}
}
private PdfPTable generateTable(Reservation reservation) {
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
cell = new PdfPCell(new Phrase("Flight Itinerary"));
cell.setColspan(2);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Flight Details"));
cell.setColspan(2);
table.addCell(cell);
table.addCell("Airlines ");
table.addCell(reservation.getFlight().getOperatingAirlines());
table.addCell("Departure City");
table.addCell(reservation.getFlight().getDepartureCity());
table.addCell("Arrival City");
table.addCell(reservation.getFlight().getArrivalCity());
table.addCell("Flight Number");
table.addCell(reservation.getFlight().getFlightNumber());
table.addCell("Departure Date");
table.addCell(reservation.getFlight().getDateOfDeparture().toString());
table.addCell("Departure Time");
table.addCell(reservation.getFlight().getEstimatedDepartureTime().toString());
cell = new PdfPCell(new Phrase("Passenger Details"));
cell.setColspan(2);
table.addCell(cell);
table.addCell("First Name");
table.addCell(reservation.getPassenger().getFirstName());
table.addCell("Last Name");
table.addCell(reservation.getPassenger().getLastName());
table.addCell("Email");
table.addCell(reservation.getPassenger().getEmail());
table.addCell("Phone");
table.addCell(reservation.getPassenger().getPhone());
return null;
}
}
EmailUtil.java
package com.doller.flightreservation.util;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
#Component
public class EmailUtil {
#Autowired
private JavaMailSender sender;
public void sendItinerary(String toAddress, String filePath) {
MimeMessage message = sender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
messageHelper.setTo(toAddress);
messageHelper.setSubject("Itinerary for your Flight");
messageHelper.setText("Please find your Itinerary attached.");
messageHelper.addAttachment("Itinearary", new File(filePath));
sender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
ReservationServiceImpl.java
package com.doller.flightreservation.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.doller.flightreservation.dto.ReservationRequest;
import com.doller.flightreservation.entities.Flight;
import com.doller.flightreservation.entities.Passenger;
import com.doller.flightreservation.entities.Reservation;
import com.doller.flightreservation.repos.FlightRepository;
import com.doller.flightreservation.repos.PassengerRepository;
import com.doller.flightreservation.repos.ReservationRepository;
import com.doller.flightreservation.util.EmailUtil;
import com.doller.flightreservation.util.PDFGenerator;
#Service
public class ReservationServiceImpl implements ReservationService {
#Autowired
FlightRepository flightRepository;
#Autowired
PassengerRepository passengerRepository;
#Autowired
ReservationRepository reservationRepository;
#Autowired
PDFGenerator pdfGenerator;
#Autowired
EmailUtil emailUtil;
#Override
public Reservation bookFlight(ReservationRequest request) {
// Make Payment
Long flightId = request.getFlightId();
Flight flight = flightRepository.findById(flightId).get();
Passenger passenger = new Passenger();
passenger.setFirstName(request.getPassengerFirstName());
passenger.setLastName(request.getPassengerLastName());
passenger.setPhone(request.getPassengerPhone());
passenger.setEmail(request.getPassengerEmail());
Passenger savedPassenger = passengerRepository.save(passenger);
Reservation reservation = new Reservation();
reservation.setFlight(flight);
reservation.setPassenger(savedPassenger);
reservation.setCheckedIn(false);
Reservation savedReservation = reservationRepository.save(reservation);
String filePath = "C:/Users/dolow/OneDrive/" + "doller_reservation_pdfs_"
+ savedReservation.getId() + ".pdf";
pdfGenerator.generateItinerary(savedReservation, filePath);
emailUtil.sendItinerary(passenger.getEmail(), filePath);
System.out.println(filePath);
return savedReservation;
}
}
At the end of generateTable you return the result:
private PdfPTable generateTable(Reservation reservation) {
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
[...]
return null;
}
You probably want to do
return table;
instead.

Groovy: Lombok #NoArgsConstructor not creating default constructor

I am using lombok 1.18.6 in my spring boot project and I have #NoArgsConstructor but still am getting org.springframework.orm.jpa.JpaSystemException: No default constructor for entity: : com.validation.entity.Client; nested exception is org.hibernate.InstantiationException: No default constructor for entity: : com.validation.entity.Client] with root cause
Below is my Client entity
import lombok.AccessLevel
import lombok.Data
import lombok.NoArgsConstructor
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.hibernate.annotations.Nationalized
import javax.persistence.CascadeType
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.OneToMany
#Data
#NoArgsConstructor(access = AccessLevel.PUBLIC)
#Entity
class Client implements Serializable {
private static final long serialVersionUID = 1L
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id
#Nationalized
#Column(unique = true, nullable = false)
private String name
#Column(nullable = false)
private boolean active
#Nationalized
#Column(unique = true, nullable = false)
private String externalId
#Fetch(value = FetchMode.SELECT)
#OneToMany(mappedBy="client", cascade=CascadeType.ALL, targetEntity = RuleSet.class)
private Set<RuleSet> ruleSets
Client(String name, boolean active, String externalId){
this.name = name
this.active = active
this.externalId = externalId
}
}
Below is my ClientRepository
import com.validation.entity.Client
import com.validation.entity.RuleDefinition
import org.springframework.data.repository.CrudRepository
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param
interface ClientRepository extends PagingAndSortingRepository<Client, Long> {
Client findByName(#Param("name")String name)
Client findByNameIgnoreCase(#Param("name")String name)
Client findByExternalId(#Param("lawId")String id)
Client findByExternalIdIgnoreCase(#Param("lawId")String id)
Client findByRuleSetsId(Long id)
Set<Client> findByNameIgnoreCaseOrExternalIdIgnoreCase(#Param("name")String name,#Param("lawId")String id)
Set<Client> findByNameContainingIgnoreCase(#Param("name")String name)
}
Can someone please help me why am I getting No default constructor for entity even with #NoArgsConstructor(access = AccessLevel.PUBLIC)
Below is the full stacktrace when I make get request https://localhost:9443/api/clients
2019-03-22 11:46:44 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: No default constructor for entity: : com.validation.entity.Client; nested exception is org.hibernate.InstantiationException: No default constructor for entity: : com.validation.entity.Client] with root cause
org.hibernate.InstantiationException: No default constructor for entity: : com.validation.entity.Client
at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:85)
at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:105)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.instantiate(AbstractEntityTuplizer.java:673)
at org.hibernate.persister.entity.AbstractEntityPersister.instantiate(AbstractEntityPersister.java:4946)
at org.hibernate.internal.SessionImpl.instantiate(SessionImpl.java:1682)
at org.hibernate.internal.SessionImpl.instantiate(SessionImpl.java:1666)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1663)
at org.hibernate.loader.Loader.getRow(Loader.java:1561)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:731)
at org.hibernate.loader.Loader.processResultSet(Loader.java:990)
at org.hibernate.loader.Loader.doQuery(Loader.java:948)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340)
at org.hibernate.loader.Loader.doList(Loader.java:2689)
at org.hibernate.loader.Loader.doList(Loader.java:2672)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506)
at org.hibernate.loader.Loader.list(Loader.java:2501)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:395)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1508)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1537)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505)
at org.hibernate.query.Query.getResultList(Query.java:135)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:74)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.readPage(SimpleJpaRepository.java:569)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:388)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:356)
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.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
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.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy134.findAll(Unknown Source)
at org.springframework.data.repository.support.PagingAndSortingRepositoryInvoker.invokeFindAll(PagingAndSortingRepositoryInvoker.java:74)
at org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory$UnwrappingRepositoryInvoker.invokeFindAll(UnwrappingRepositoryInvokerFactory.java:158)
at org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource(RepositoryEntityController.java:202)
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:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
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.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
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.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.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
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:93)
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.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
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:200)
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:199)
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.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:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
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)
Below is the decompiled Client class
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.Nationalized;
#Entity
public class Client
implements Serializable, GroovyObject
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Nationalized
#Column(nullable=false, unique=true)
private String name;
#Column(nullable=false)
private boolean active;
#Nationalized
#Column(nullable=false, unique=true)
private String externalId;
#Fetch(FetchMode.SELECT)
#OneToMany(targetEntity=RuleSet.class, mappedBy="client", cascade={javax.persistence.CascadeType.ALL})
private Set<RuleSet> ruleSets;
public Client(String name, boolean active, String externalId)
{
MetaClass localMetaClass = $getStaticMetaClass();this.metaClass = localMetaClass;String str1 = name;this.name = ((String)ShortTypeHandling.castToString(str1));
boolean bool = active;this.active = DefaultTypeTransformation.booleanUnbox(Boolean.valueOf(bool));
String str2 = externalId;this.externalId = ((String)ShortTypeHandling.castToString(str2));
}
}
Based on your de-compiled output you are using Groovy, not Java. Lombok doesn't work well with Groovy. Your decompiled code shows this, there are no Lombok augmentations e.g. getters are not created by #Data.
If you plan to continue mixing Lombok with Groovy you need to revisit your project setup. Personally I'd not mix these two things.
Please try this it helped to me for the #NoArgsConstructor. Now lombok works and no error displayed.
Add Lombok plugin besides dependency like this:
plugins {
id "io.freefair.lombok" version "6.4.1"
}
dependencies {
implementation 'org.projectlombok:lombok:1.16.18'
}
Have a nice day! Enjoy coding!
It is simply not true that Lombok doesn't work well with Java, like stated above and in Lombok doesn't work well with Groovy.
There is no problem with consuming Lombok annotated Java Object in Groovy code, see also examples here
here
Lombok annotations in Groovy code are simply ignored. Groovy does not support Lombok annotations. So this more a issue of Groovy than visa versa.
That relativizes the statements not to use both. I think that's is the whole point of JVM based languages : the "relative" good interoperability (Java, Groovy, JRuby, Kotlin etc).

EntityManager and SessionHolder error in SpringBoot Rest API

The above query is regarding the project that I am working on:
PROJECT:
I have a simple REST based API project using SpringBoot and hibernate where I need to build a registration and login mechanism using GET and POST requests.
Whenever I am trying to make a POST request to create a resource(create a new user in this case) I get the following error on POSTMAN and also Eclipse IDE:
POST REQUEST I made using POSTMAN
{
"userId": "12345",
"pin": "1234"
}
ERROR ON POSTMAN While Making a POST REQUEST
{
"timestamp": 1551809931747,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.ClassCastException",
"message": "org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate4.SessionHolder",
"path": "/employee/register"
}
FULL STACK TRACE OF THE ERROR
java.lang.ClassCastException: org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate4.SessionHolder
at org.springframework.orm.hibernate4.HibernateTransactionManager.doGetTransaction(HibernateTransactionManager.java:380) ~[spring-orm-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:341) ~[spring-tx-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:461) ~[spring-tx-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) ~[spring-tx-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671) ~[spring-aop-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at com.cerner.project.dao.EmployeeDAO$$EnhancerBySpringCGLIB$$1b4cb760.registerUser(<generated>) ~[classes/:na]
at com.cerner.project.controller.EmployeeController.registerUser(EmployeeController.java:28) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_201]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_201]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:849) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:760) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) ~[spring-boot-1.5.19.RELEASE.jar:1.5.19.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:111) ~[spring-boot-actuator-1.5.19.RELEASE.jar:1.5.19.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103) ~[spring-boot-actuator-1.5.19.RELEASE.jar:1.5.19.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.22.RELEASE.jar:4.3.22.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.37.jar:8.5.37]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_201]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_201]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.37.jar:8.5.37]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_201]
What might be the issue causing this error? All I am trying to do is a simple POST.
Below are my files:
User.Java
package com.cerner.project.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="user")
public class User {
#Id
#Column(name="user_id")
private int userId;
#Column(name="pin")
//#ColumnTransformer(read = "sha1(pin)",write = "sha1(?)")
private String pin;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="user_id")
private List<UserLog> userLog=new ArrayList<UserLog>();
public List<UserLog> getUserLog() {
return userLog;
}
public void setUserLog(List<UserLog> userLog) {
this.userLog = userLog;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public User() {
}
public User(int userId, String pin) {
this.userId = userId;
this.pin= pin;
}
//CLOVER:OFF
#Override
public String toString() {
return "User [userId=" + userId + ", pin=" + pin + "]";
}
//CLOVER:ON
}
EmployeeDao.Java
package com.cerner.project.dao;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.cerner.project.model.Team;
import com.cerner.project.model.User;
import com.cerner.project.model.UserLog;
//#Service
#Repository
#Transactional
public class EmployeeDAO {
#Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
public User registerUser(User user) {
int userId=user.getUserId();
user.setUserId(userId);
String userPin=user.getPin();
user.setPin(userPin);
return user;
}
public List<User> getAllUsers() {
List<User> users=new ArrayList<User>();
User user1=new User(11111,"1234");
User user2=new User(22222,"4321");
users.add(user1);
users.add(user2);
getSession().beginTransaction();
getSession().save(user1);
getSession().save(user1);
getSession().getTransaction().commit();
return users;
}
}
EmployeeController.Java
package com.cerner.project.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cerner.project.dao.EmployeeDAO;
import com.cerner.project.model.User;
#RestController
#RequestMapping("/employee")
public class EmployeeController {
#Autowired
private EmployeeDAO employeeDao;
#RequestMapping("/test")
public String test() {
return "Hello World!";
}
#PostMapping("/register")
public String registerUser(#RequestBody User user) {
employeeDao.registerUser(user);
return("SUCCESS");
}
#GetMapping("/getUsers")
public List<User> getAllUsers(){
return employeeDao.getAllUsers();
}
}
DBConfiguration.Java
package com.cerner.project.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#PropertySource(value = { "classpath:application.properties" })
#Configuration
//#EnableTransactionManagement
public class DBConfiguration {
#Value("${jdbc.driverClassName}")
private String driverClass;
#Value("${jdbc.url}")
private String url;
#Value("${jdbc.username}")
private String username;
#Value("${jdbc.password}")
private String password;
#Value("${hibernate.dialect}")
private String dialect;
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(url, username, password);
dataSource.setDriverClassName(driverClass);
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(getDataSource());
factory.setHibernateProperties(hibernateProperties());
factory.setPackagesToScan(new String[] { "com.cerner.project" });
return factory;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", dialect);
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory factory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(factory);
return transactionManager;
}
}
Change #SpringBootApplication to
#SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class)
With the release of Hibernate 5.2 the SessionFactory extends the EntityManagerFactory interface. This leads to the SessionFactory also being an EntityManagerFactory.
In previous hibernate releases this wasn't the case.
The easy solution is to downgrade the hibernate version to a version < 5.2 as there is no solution for Spring 5.0 (there will be in Spring 5.1).
You can Refer 1 2 these for more Details
EDIT:
When you write exclude=HibernateJpaAutoConfiguration.class as a result
#SpringBootApplication
will not consider that particular class for further execution. As you can see in the image HibernateJpaAutoConfiguration already implemented some classes(which may implement others) for which you don't need to configure anything or make it easy to use, For example, LocalContainerEntityManagerFactoryBean.class. As you have excluded the class you must need to manually do the things which HibernateJpaAutoConfiguration.class done for you.

Resources