I am trying to parse xml to java objects in spring batch and spring boot using XStreamMarshaller. everything was working fine and i was able to parse the file and get the required java objects but as soon as i introduced taskexecutor multithreading to improve my performance it starts to give me error which i'm unable to fix. I searched for the issue but didn't find any appropriate cause or response. Please help me to fix the issue or redirect me to some appropriate link which may solve my problem.
Thanks in advance...
BatchxmlApplication.java
#SpringBootApplication
#EnableBatchProcessing
public class BatchxmlApplication {
public static void main(String[] args) {
SpringApplication.run(BatchxmlApplication.class, args);
}
}
XmlConfiguration.java
#Configuration
public class XmlConfiguration
{
#Autowired
JobBuilderFactory jobBuilderFactory;
#Autowired
StepBuilderFactory stepBuilderFactory;
#StepScope
#Bean(name="xmlReader")
public StaxEventItemReader<StudentDTO> reader()
{
StaxEventItemReader<StudentDTO> xmlFileReader = new StaxEventItemReader<>();
xmlFileReader.setResource(new ClassPathResource("students.xml"));
xmlFileReader.setFragmentRootElementName("student");
Map<String, Class<?>> aliases = new HashMap<>();
aliases.put("student", StudentDTO.class);
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.setAliases(aliases);
xmlFileReader.setUnmarshaller(xStreamMarshaller);
return xmlFileReader;
}
#Bean(name="xmlProcessor")
public ItemProcessor<StudentDTO, StudentDTO> processor()
{
return new Processor();
}
#Bean(name="xmlWriter")
public ItemWriter<StudentDTO> writer()
{
return new Writer();
}
#Bean(name="xmljobListener")
public JobExecutionListenerSupport jobListener()
{
return new JobListener();
}
#JobScope
#Bean(name="xmltaskExecutor")
public ThreadPoolTaskExecutor taskExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(50);
executor.setMaxPoolSize(100);
return executor;
}
#Bean(name="xmlStep")
public Step xmlFileToDatabaseStep()
{
return stepBuilderFactory.get("xmlStep")
.<StudentDTO, StudentDTO>chunk(1)
.reader(this.reader())
.processor(this.processor())
.writer(this.writer())
.taskExecutor(this.taskExecutor())
.build();
}
#Bean(name="xmlJob")
public Job xmlFileToDatabaseJob(#Autowired #Qualifier("xmlStep") Step step)
{
return jobBuilderFactory
.get("xmlJob"+new Date())
.incrementer(new RunIdIncrementer())
.listener(this.jobListener())
.flow(step)
.end()
.build();
}
}
Processor.java
public class Processor implements ItemProcessor<StudentDTO, StudentDTO>
{
#Override
public StudentDTO process(StudentDTO item) throws Exception
{
StudentDTO st = item;
return st;
}
}
Writer.java
public class Writer implements ItemWriter<StudentDTO>
{
#Override
public void write(List<? extends StudentDTO> items) throws Exception
{
items.stream().forEach(i->System.err.println(i));
}
}
StudentDTO.java
#XmlRootElement(name="student")
public class StudentDTO
{
private String emailAddress;
private String name;
private String purchasedPackage;
... getter,setter and constructor
}
XMLBatchController.java
#CrossOrigin("*")
#RestController
public class XMLBatchController
{
#Autowired
#Qualifier("xmlJob")
Job job;
#Autowired
private JobLauncher jobLauncher;
#GetMapping(value="/run")
public String run() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException
{
long st = System.currentTimeMillis();
JobParametersBuilder builder = new JobParametersBuilder();
builder.addDate("date", new Date());
jobLauncher.run(job, builder.toJobParameters());
return "The processing took = "+(System.currentTimeMillis()-st)+" ms<p>Timestamp = "+new Date();
}
}
JobListener.java
public class JobListener extends JobExecutionListenerSupport
{
#Autowired
#Qualifier("xmltaskExecutor")
ThreadPoolTaskExecutor taskExecutor;
#Override
public void afterJob(JobExecution jobExecution)
{
if(jobExecution.getStatus() == BatchStatus.COMPLETED)
{
taskExecutor.shutdown();
System.err.println("*****************");
System.err.println("\tJob Completed");
System.err.println("*****************");
}
else
{
System.err.println("*****************");
System.err.println("\tJob Failed");
System.err.println("*****************");
}
}
#Override
public void beforeJob(JobExecution jobExecution)
{
}
}
students.xml
<students>
<student>
<name>Tony Tester</name>
<emailAddress>tony.tester#gmail.com</emailAddress>
<purchasedPackage>master</purchasedPackage>
</student>
<student>
<name>Nick Newbie</name>
<emailAddress>nick.newbie#gmail.com</emailAddress>
<purchasedPackage>starter</purchasedPackage>
</student>
<student>
<name>Ian Intermediate</name>
<emailAddress>ian.intermediate#gmail.com</emailAddress>
<purchasedPackage>intermediate</purchasedPackage>
</student>
</students>
ErrorLog
2019-06-20 12:26:05.039 INFO 12108 --- [nio-9090-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/batch] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-06-20 12:26:05.039 INFO 12108 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-06-20 12:26:05.048 INFO 12108 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 9 ms
2019-06-20 12:26:05.350 INFO 12108 --- [nio-9090-exec-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=xmlJobThu Jun 20 12:25:57 IST 2019]] launched with the following parameters: [{date=1561013765206}]
2019-06-20 12:26:05.411 INFO 12108 --- [nio-9090-exec-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [xmlStep]
2019-06-20 12:26:05.497 INFO 12108 --- [nio-9090-exec-1] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'scopedTarget.xmltaskExecutor'
2019-06-20 12:26:05.642 ERROR 12108 --- [nio-9090-exec-1] o.s.batch.core.step.AbstractStep : Encountered an error executing step xmlStep in job xmlJobThu Jun 20 12:25:57 IST 2019
org.springframework.oxm.UnmarshallingFailureException: XStream unmarshalling exception; nested exception is com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception : java.util.NoSuchElementException
cause-message : null
class : com.example.demo.dto.StudentDTO
required-type : com.example.demo.dto.StudentDTO
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /student
line number : 2
version : 5.1.8.RELEASE
-------------------------------
at org.springframework.oxm.xstream.XStreamMarshaller.convertXStreamException(XStreamMarshaller.java:851) ~[spring-oxm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.oxm.xstream.XStreamMarshaller.doUnmarshal(XStreamMarshaller.java:829) ~[spring-oxm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.oxm.xstream.XStreamMarshaller.unmarshalXmlStreamReader(XStreamMarshaller.java:786) ~[spring-oxm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.oxm.xstream.XStreamMarshaller.unmarshalXmlEventReader(XStreamMarshaller.java:777) ~[spring-oxm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.oxm.support.AbstractMarshaller.unmarshalStaxSource(AbstractMarshaller.java:411) ~[spring-oxm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.oxm.support.AbstractMarshaller.unmarshal(AbstractMarshaller.java:354) ~[spring-oxm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.batch.item.xml.StaxEventItemReader.doRead(StaxEventItemReader.java:255) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:92) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader$$FastClassBySpringCGLIB$$ebb633d0.invoke(<generated>) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:136) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:124) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.batch.item.xml.StaxEventItemReader$$EnhancerBySpringCGLIB$$f905f63e.read(<generated>) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:94) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.item.SimpleChunkProvider.read(SimpleChunkProvider.java:161) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:119) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:113) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:407) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:331) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:273) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate$ExecutingRunnable.run(TaskExecutorRepeatTemplate.java:262) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_144]
at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_144]
Caused by: com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception : java.util.NoSuchElementException
cause-message : null
class : com.example.demo.dto.StudentDTO
required-type : com.example.demo.dto.StudentDTO
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /student
line number : 2
version : 5.1.8.RELEASE
-------------------------------
at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:70) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1230) ~[xstream-1.4.9.jar:1.4.9]
at org.springframework.oxm.xstream.XStreamMarshaller.doUnmarshal(XStreamMarshaller.java:826) ~[spring-oxm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
... 32 common frames omitted
Caused by: java.util.NoSuchElementException: null
at org.springframework.batch.item.xml.stax.DefaultFragmentEventReader.nextEvent(DefaultFragmentEventReader.java:112) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.util.xml.XMLEventStreamReader.next(XMLEventStreamReader.java:277) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at com.thoughtworks.xstream.io.xml.StaxReader.pullNextEvent(StaxReader.java:58) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.io.xml.AbstractPullReader.readRealEvent(AbstractPullReader.java:148) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.io.xml.AbstractPullReader.readEvent(AbstractPullReader.java:135) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.io.xml.AbstractPullReader.hasMoreChildren(AbstractPullReader.java:87) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.io.ReaderWrapper.hasMoreChildren(ReaderWrapper.java:32) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:333) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:281) ~[xstream-1.4.9.jar:1.4.9]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72) ~[xstream-1.4.9.jar:1.4.9]
... 39 common frames omitted
*****************
Job Failed
*****************
2019-06-20 12:26:05.693 INFO 12108 --- [nio-9090-exec-1] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'scopedTarget.xmltaskExecutor'
2019-06-20 12:26:05.694 INFO 12108 --- [nio-9090-exec-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=xmlJobThu Jun 20 12:25:57 IST 2019]] completed with the following parameters: [{date=1561013765206}] and the following status: [FAILED]
2019-06-20 12:35:00.318 INFO 12108 --- [n(15)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2019-06-20 12:35:00.327 INFO 12108 --- [n(15)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-06-20 12:35:00.329 INFO 12108 --- [n(15)-127.0.0.1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2019-06-20 12:35:00.362 INFO 12108 --- [n(15)-127.0.0.1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
As mentioned in its Javadoc, StaxEventItemReader is not thread safe. So using it in a multi-threaded step is not correct.
You need to wrap it in a SynchronizedItemStreamReader. In your case, it would be something like:
#StepScope
#Bean(name="xmlReader")
public SynchronizedItemStreamReader<StudentDTO> reader()
{
StaxEventItemReader<StudentDTO> xmlFileReader = new StaxEventItemReader<>();
xmlFileReader.setResource(new ClassPathResource("students.xml"));
xmlFileReader.setFragmentRootElementName("student");
Map<String, Class<?>> aliases = new HashMap<>();
aliases.put("student", StudentDTO.class);
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.setAliases(aliases);
xmlFileReader.setUnmarshaller(xStreamMarshaller);
SynchronizedItemStreamReader< StudentDTO> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
synchronizedItemStreamReader.setDelegate(xmlFileReader);
return synchronizedItemStreamReader;
}
Related
I work on simple authentication app using spring security & encounter by an access denied error. I must mention that registration works perfectly & I've already created 1 record with bcrypted password but on login I'm failed to understand that what did I miss. Grateful for the help
User.java
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String username;
private String email;
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority>authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new
Authority(ur.getRole().getName())));
return authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserSecurityService userSecurityService;
public SecurityConfig(UserSecurityService userSecurityService) {
this.userSecurityService = userSecurityService;
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userSecurityService).passwordEncoder
(passwordEncoder());
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws
Exception {return super.authenticationManagerBean();
}
}
UserSecurityService (loaduser)
#Service
public class UserSecurityService implements UserDetailsService {
private static final Logger LOG =
LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = userRepository.findUserByUsername(username);
if (null == user) {
LOG.warn("Username {} not found", username);
throw new UsernameNotFoundException("Username " + username + "
not found");
}
return user;
}
}
AuthController
#RestController
#RequestMapping("/api/auth")
public class AuthController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private UserService userService;
#PostMapping("/register")
public ResponseEntity<User> register(#RequestBody User user) throws Exception {
return new ResponseEntity<>(userService.register(user), HttpStatus.OK);
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody String username, String password ) throws
Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
username, password
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
}
Error
2022-01-14 14:49:13.604 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Starting
BankingApiApplication using Java 11.0.12 on LAPTOP-BQ48GM36 with PID
24600 (B:\spring\bankingAPI\target\classes started by The Kash in
B:\spring\bankingAPI)
2022-01-14 14:49:13.605 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : No active profile set,
falling back to default profiles: default
2022-01-14 14:49:13.673 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults
active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-01-14 14:49:13.674 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : For additional web related
logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-01-14 14:49:14.557 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA
repositories in DEFAULT mode.
2022-01-14 14:49:14.646 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 74 ms. Found 2 JPA repository interfaces.
2022-01-14 14:49:15.876 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8088 (http)
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.56]
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain]
w.s.c.ServletWebServerApplicationContext : Root
WebApplicationContext:
initialization completed in 2334 ms
2022-01-14 14:49:16.264 INFO 24600 --- [ restartedMain]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2022-01-14 14:49:16.332 INFO 24600 --- [ restartedMain]
org.hibernate.Version : HHH000412: Hibernate ORM
core
version 5.6.3.Final
2022-01-14 14:49:16.542 INFO 24600 --- [ restartedMain]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final}
2022-01-14 14:49:16.661 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-14 14:49:17.128 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed.
2022-01-14 14:49:17.145 INFO 24600 --- [ restartedMain]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.MySQL57Dialect
2022-01-14 14:49:18.469 INFO 24600 --- [ restartedMain]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
2022-01-14 14:49:18.478 INFO 24600 --- [ restartedMain]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2022-01-14 14:49:19.173 WARN 24600 --- [ restartedMain]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is
enabled by default. Therefore, database queries may be performed
during
view rendering. Explicitly configure spring.jpa.open-in-view to
disable
this warning
2022-01-14 14:49:19.453 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/**', GET]
2022-01-14 14:49:19.455 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/auth/**']
2022-01-14 14:49:19.456 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [authenticated] for any request
2022-01-14 14:49:19.468 INFO 24600 --- [ restartedMain]
o.s.s.web.DefaultSecurityFilterChain : Will secure any request
with
[org.springframework.security.web.context.request.async.
WebAsyncManagerIntegrationFilter#4b607819,
org.springframework.security.web.context.SecurityContextPersistence
Filter#146dcdcf,
org.springframework.security.web.header.HeaderWriterFilter#74f0174b,
org.springframework.security.web.authentication.logout.
LogoutFilter#839ff7f,
org.springframework.security.web.authentication.www.
BasicAuthenticationFilter#4f78b9a2,
org.springframework.security.web.savedrequest.
RequestCacheAwareFilter#7e2b3eef,
org.springframework.security.web.servletapi.SecurityContextHolder
AwareRequestFilter#1996d59a,
org.springframework.security.web.authentication.Anonymous
AuthenticationFilter#d82cd0b,
org.springframework.security.web.session.SessionManagement
Filter#47842f0b,
org.springframework.security.web.access.ExceptionTranslation
Filter#6fdc8d32, org.springframework.security.web.access.intercept.
FilterSecurityInterceptor#3619bc38]
2022-01-14 14:49:19.922 INFO 24600 --- [ restartedMain]
o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is
running
on port 35729
2022-01-14 14:49:19.959 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s):
8088 (http) with context path ''
2022-01-14 14:49:19.970 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Started
BankingApiApplication
in 6.835 seconds (JVM running for 7.645)
2022-01-14 14:49:51.914 INFO 24600 --- [nio-8088-exec-2] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring
DispatcherServlet
'dispatcherServlet'
2022-01-14 14:49:51.915 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2022-01-14 14:49:51.916 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Completed initialization
in
1 ms
2022-01-14 14:49:51.931 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /api/auth/login
2022-01-14 14:49:51.936 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:51.939 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:51.940 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.session.SessionManagementFilter : Request requested invalid
session id 1E5E812360CC1B8291311CA85ACAC55A
2022-01-14 14:49:51.945 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.i.FilterSecurityInterceptor : Authorized filter
invocation
[POST /api/auth/login] with attributes [permitAll]
2022-01-14 14:49:51.946 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST
/api/auth/login
Hibernate: select user0_.id as id1_7_, user0_.email as email2_7_,
user0_.name as name3_7_, user0_.password as password4_7_,
user0_.primary_account_id as primary_6_7_, user0_.savings_account_id
as
savings_7_7_, user0_.username as username5_7_ from users user0_ where
user0_.username=?
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2]
c.k.b.s.serviceImpl.UserSecurityService : Username {
"username": "seeshee",
"password": "12345"
} not found
2022-01-14 14:49:52.313 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user '{
"username": "seeshee",
"password": "1234"
}'
2022-01-14 14:49:52.698 WARN 24600 --- [nio-8088-exec-2]
o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom
instance for session ID generation using [SHA1PRNG] took [364]
milliseconds.
2022-01-14 14:49:52.700 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.s.HttpSessionRequestCache : Saved request
http://localhost:8088/api/auth/login to session
2022-01-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using
Reque
tHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expec
edHeaderValue=XMLHttpRequest]
2022-1-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using
default entry point
org.springframework.security.web.authentication.www.
BasicAuthenticationEntryPoint#691634d7
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder
to complete request
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /error
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST /error
2022-01-14 14:49:52.721 DEBUG 24600 --- [nio-8088-exec-2]
a.DefaultWebInvocationPrivilegeEvaluator : filter invocation [/error]
denied for AnonymousAuthenticationToken [Principal=anonymousUser,
Credentials=[PROTECTED], Authenticated=true,
Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1,
SessionId=BAFE9322A4A2705325C4B6540915129E], Granted Authorities=
[ROLE_ANONYMOUS]]
org.springframework.security.access.AccessDeniedException: Access is
denied
at
org.springframework.security.access.vote.AffirmativeBased.
decide(AffirmativeBased.java:73)
~[spring-security-core-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWe
bInvocationPrivilegeEvaluator.java:100) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWebInvocationPrivilegeEvaluator.java:67) ~[spring-security-
web-
5.6.1.jar:5.6.1]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
isAllowed
(ErrorPageSecurityFilter.java:84) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:72) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:66) ~[spring-boot-2.6.2.jar:2.6.2]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
ApplicationFilterChain.
java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.jav
a:327) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.invoke
(FilterSecurityInterceptor.java:106) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.doFilter
(FilterSecurityInterceptor.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
ExceptionTranslationFilter.doFilter
(ExceptionTranslationFilter.java:122) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.access.ExceptionTranslationFilter.
doFilter
(ExceptionTranslationFilter.java:116) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter
.doFilter
(SessionManagementFilter.java:87) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter.
doFilter
(SessionManagementFilter.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain
.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.
AnonymousAuthenticationFilter.doFilter
(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.servletapi.
SecurityContextHolderAwareRequestFilter.
doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-
security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.savedrequest.
RequestCacheAwareFilter.doFilter
(RequestCacheAwareFilter.java:63) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(
OncePerRequestFilter.java:102)
~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$VirtualFilter
Chain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal
(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilter
(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate
(DelegatingFilterProxy.java:354) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter
(DelegatingFilterProxy.java:267) ~
[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal
(RequestContextFilter.java:100) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.invoke
(ApplicationDispatcher.java:711) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.processRequest
(ApplicationDispatcher.java:461) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.doForward
(ApplicationDispatcher.java:385) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.forward
(ApplicationDispatcher.java:313) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.custom
(StandardHostValve.java:403) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.status
(StandardHostValve.java:249) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder to complete request
Your logs say this:
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2] c.k.b.s.serviceImpl.UserSecurityService :
Username { "username": "seeshee", "password": "12345" } not found
If we look in your code we can see the following line:
login(#RequestBody String username, String password )
This is your faulty code line, as it doesn't do what you think it does. You think it will take the json and extract the two parameters username and password and set these. But what it actually does is that the #RequestBody will take the entire body (the json) and set it to the parameter that is defined on, which is username.
So what spring is doing is that it will extract the entire json body and place it into the username string.
Then you try to use that to login, and then you get the error message posted above.
What you need to do is to create a holder class that spring can deserialize into.
public class RequestBody {
public RequestBody(String username, String password) {
this.username = username;
this.password = password;
}
// getters, setters
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody RequestBody requestBody ) throws Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
requestBody.getUsername(), requestBody.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
You can read about how to use requestbody here:
Spring’s RequestBody and ResponseBody Annotation
I have simple application that is trying consume Rest service:
#SpringBootApplication
public class ConsumingRestApplication
{
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args)
{
SpringApplication.run(ConsumingRestApplication.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder)
{
return builder.build();
}
#Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception
{
return args -> {
try
{
restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
} catch (RestClientException e)
{
e.printStackTrace();
}
};
}
}
Quote class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
Got error :
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote] and content type [application/json;charset=UTF-8]
Whole exception trace:
2020-10-19 12:39:04.984 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : Starting ConsumingRestApplication on GM with PID 8328 (C:\gdrive\java_test\consumingrest\build\classes\java\main started by g in C:\gdrive\java_test\consumingrest)
2020-10-19 12:39:04.987 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : No active profile set, falling back to default profiles: default
2020-10-19 12:39:05.070 INFO 8328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-10-19 12:39:05.070 INFO 8328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-10-19 12:39:06.843 INFO 8328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-10-19 12:39:06.856 INFO 8328 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-10-19 12:39:06.857 INFO 8328 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.38]
2020-10-19 12:39:06.957 INFO 8328 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-10-19 12:39:06.957 INFO 8328 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1887 ms
2020-10-19 12:39:07.204 INFO 8328 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-10-19 12:39:07.395 INFO 8328 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-10-19 12:39:07.603 INFO 8328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-10-19 12:39:07.617 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : Started ConsumingRestApplication in 3.076 seconds (JVM running for 3.545)
2020-10-19 12:39:07.786 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:07.786 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.541 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.542 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.544 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.545 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote] and content type [application/json;charset=UTF-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:126)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:741)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:315)
at com.example.consumingrest.ConsumingRestApplication.lambda$run$0(ConsumingRestApplication.java:37)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at com.example.consumingrest.ConsumingRestApplication.main(ConsumingRestApplication.java:21)
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.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
What is starting point o solving this problem? What logic I should go to find problem?
I believe you are missing Value object or must be a wrong import. Along with that you need to add getter methods for the field if they are private, when you are returning that object directly in the response, here is how i have done it:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
#RestController
public static class Test {
#Autowired
private RestTemplate restTemplate;
#GetMapping
public Quote test() {
return restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
}
}
public static class Quote {
private String type;
private Value value;
public String getType() {
return type;
}
public Value getValue() {
return value;
}
}
public static class Value {
private Long id;
private String quote;
public Long getId() {
return id;
}
public String getQuote() {
return quote;
}
}
}
I have something very similar to the code below (I had to do some obfiscation). I am getting an Application Failed to Start error. Code not shown are datasource bean and spring boot application class. When I put breakpoints in and all run in debug, all beans appear to be created except the Job and Step bean, which seem to be skipped over entirely. I am not sure how to diagnose further. Seems to be some Spring Magic issues. Any ideas are greatly appreciated.
Here is the exception:
2020-08-23 11:26:50.264 INFO 12195 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-23 11:26:50.265 INFO 12195 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-08-23 11:26:50.382 INFO 12195 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-23 11:26:50.383 INFO 12195 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2276 ms
2020-08-23 11:26:57.552 WARN 12195 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'databaseCursorStep' defined in class path resource [/com/configuration/BatchConfig.class]: Unsatisfied dependency expressed through method 'databaseCursorStep' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.item.ItemReader<com.dto.StuffDto>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=databaseCursorItemReader)}
2020-08-23 11:26:57.572 INFO 12195 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-08-23 11:26:57.603 INFO 12195 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-23 11:26:57.908 ERROR 12195 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Parameter 0 of method databaseCursorStep in com.configuration.BatchConfig required a bean of type 'org.springframework.batch.item.ItemReader' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Qualifier(value=databaseCursorItemReader)
Action:
Consider defining a bean of type 'org.springframework.batch.item.ItemReader' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:46088', transport: 'socket'
Process finished with exit code 1
Here is the code:
#Configuration
#EnableBatchProcessing
public class BatchConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
private static final String GET_DATA =
"SELECT " +
"stuffA, " +
"stuffB, " +
"FROM STUFF_TABLE " +
"ORDER BY stuffA ASC";
#Bean
public ItemReader<StuffDto> itemReader(DataSource dataSource) {
return new JdbcCursorItemReaderBuilder<StuffDto>()
.name("cursorItemReader")
.dataSource(dataSource)
.sql(GET_DATA)
.rowMapper(new BeanPropertyRowMapper<>(StuffDto.class))
.build();
}
#Bean
ItemProcessor<StuffDto, StuffDto> databaseXmlItemProcessor() {
return new QueryLoggingProcessor();
}
#Bean
public ItemWriter<StuffDto> databaseCursorItemWriter() {
return new LoggingItemWriter();
}
#Bean
public Step databaseCursorStep(#Qualifier("databaseCursorItemReader") ItemReader<StuffDto> reader,
#Qualifier("databaseCursorItemWriter") ItemWriter<StuffDto> writer,
StepBuilderFactory stepBuilderFactory) {
return stepBuilderFactory.get("databaseCursorStep")
.<StuffDto, StuffDto>chunk(1)
.reader(reader)
.writer(writer)
.build();
}
#Bean
public Job databaseCursorJob(#Qualifier("databaseCursorStep") Step exampleJobStep,
JobBuilderFactory jobBuilderFactory) {
return jobBuilderFactory.get("databaseCursorJob")
.incrementer(new RunIdIncrementer())
.flow(exampleJobStep)
.end()
.build();
}
}
Your Qualifier Bean name is itemReader not databaseCursorItemReader. Either change the method name or change to databaseCursorStep(#Qualifier("itemReader")
#Bean
public Step databaseCursorStep(#Qualifier("itemReader") ItemReader<StuffDto> reader,
#Qualifier("databaseCursorItemWriter") ItemWriter<StuffDto> writer,
StepBuilderFactory stepBuilderFactory) {
return stepBuilderFactory.get("databaseCursorStep")
.<StuffDto, StuffDto>chunk(1)
.reader(reader)
.writer(writer)
.build();
}
#Bean
public ItemReader<StuffDto> itemReader(DataSource dataSource) {
return new JdbcCursorItemReaderBuilder<StuffDto>()
.name("cursorItemReader")
.dataSource(dataSource)
.sql(GET_DATA)
.rowMapper(new BeanPropertyRowMapper<>(StuffDto.class))
.build();
}
I am trying to fetch data from database in my spring boot application. I am using hibernate libraries. Below is my entity class:
#SuppressWarnings("serial")
#Entity
#Table(name = "MU_GM_CIRCULARS")
public class GmCirculars extends ParentEntity implements Serializable {
private BigDecimal id;
private Date createdOn;
private String title;
private BigDecimal serialNo;
private BigDecimal year;
private BigDecimal active;
private BigDecimal organizationId;
private BigDecimal showOnDashboard;
public GmCirculars() {
super();
}
public GmCirculars(BigDecimal id) {
super();
this.id = id;
}
public GmCirculars(BigDecimal id, BigDecimal createdById, Date createdOn, String title, BigDecimal serialNo,
BigDecimal year ,BigDecimal documentId, BigDecimal typeId) {
super();
this.id = id;
this.createdOn = createdOn;
this.title = title;
this.serialNo = serialNo;
this.year = year;
}
#Id
#Column(name = "ID")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="MU_GM_CIRCULARS_SEQ")
#SequenceGenerator(name="MU_GM_CIRCULARS_SEQ",sequenceName="MU_GM_CIRCULARS_SEQ",allocationSize=1)
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
#Column(name="created_on")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
#Column(name="title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="serial_no")
public BigDecimal getSerialNo() {
return serialNo;
}
public void setSerialNo(BigDecimal serialNo) {
this.serialNo = serialNo;
}
#Column(name="year")
public BigDecimal getYear() {
return year;
}
public void setYear(BigDecimal year) {
this.year = year;
}
#Column(name = "org_id")
public BigDecimal getOrganizationId() {
return organizationId;
}
public void setOrganizationId(BigDecimal organizationId) {
this.organizationId = organizationId;
}
#Column(name="show_on_dashboard")
public BigDecimal getShowOnDashboard() {
return showOnDashboard;
}
public void setShowOnDashboard(BigDecimal showOnDashboard) {
this.showOnDashboard = showOnDashboard;
}
#Column(name = "active")
public BigDecimal isActive() {
return active;
}
public void setActive(BigDecimal active) {
this.active = active;
}
}
Here's the class with the method that fetches the data:
#Repository
#Transactional
#SuppressWarnings("unchecked")
public class GmCircularsDaoImpl extends ParentDAO implements IGmCircularsDAO {
#Override
public List<GmCirculars> find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows) {
Session session = null;
List<GmCirculars> discounts = null;
try {
if (null != obj) {
session= this.getSession();
Criteria criteria = session.createCriteria(GmCirculars.class);
if (null != obj.getId() && !BigDecimal.ZERO.equals(obj.getId())) {
criteria.add(Restrictions.eq("id", obj.getId()));
}
if (StringUtil.isNotNullOrEmpty(obj.getTitle())) {
criteria.add(Restrictions.ilike("title", obj.getTitle(), MatchMode.ANYWHERE));
}
if(null != obj.getOrganizationId()) {
criteria.add(Restrictions.eq("organizationId", obj.getOrganizationId()));
}
if (null != obj.getSerialNo() && !BigDecimal.ZERO.equals(obj.getSerialNo())) {
criteria.add(Restrictions.eq("serialNo", obj.getSerialNo()));
}
if (null != obj.getYear() && !BigDecimal.ZERO.equals(obj.getYear())) {
criteria.add(Restrictions.eq("year", obj.getYear()));
}
if (activeOnly) {
criteria.add(Restrictions.eq("active", BigDecimal.ONE));
} else {
criteria.add(Restrictions.or(Restrictions.ne("active", CommonConstants.DELETED_STATUS), Restrictions.isNull("active"))); //Except for deleted ones -> NVL(active,2)
}
criteria.setFirstResult(startOffset);
criteria.setMaxResults(maxRows);
criteria.addOrder(Order.desc("id"));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
System.out.println("criteria: "+ criteria.toString());
discounts = criteria.list();
System.out.println("returned list from db:"+discounts);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return discounts;
}
I try to access the database exactly on the line:
discounts = criteria.list();
which is in the method find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows)
When I run my code, I am getting the following errors.
java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:195) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:876)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1498)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatementWrapper.executeQuery(OracleStatementWrapper.java:406)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
~[commons-dbcp-1.4.jar:1.4]
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:42)
~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.sequenceInformationList(JdbcEnvironmentImpl.java:403)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.(JdbcEnvironmentImpl.java:268)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.(InFlightMetadataCollectorImpl.java:175)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
................................................................................
2020-02-03 09:16:11.269 INFO 9952 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-02-03 09:16:11.281 INFO 9952 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-02-03 09:16:11.299 INFO 9952 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-02-03 09:16:11.367 WARN 9952 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2020-02-03 09:16:11.368 INFO 9952 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2020-02-03 09:16:11.470 WARN 9952 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-02-03 09:16:11.646 INFO 9952 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-02-03 09:16:12.754 WARN 9952 --- [ restartedMain] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of spring.cloud.loadbalancer.ribbon.enabled to false or remove spring-cloud-starter-netflix-ribbon from your project.
2020-02-03 09:16:12.794 INFO 9952 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-02-03 09:16:12.846 INFO 9952 --- [ restartedMain] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING
2020-02-03 09:16:12.900 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1
2020-02-03 09:16:13.231 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson
2020-02-03 09:16:13.231 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson
2020-02-03 09:16:13.385 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml
2020-02-03 09:16:13.385 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml
2020-02-03 09:16:13.586 INFO 9952 --- [ restartedMain] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Disable delta property : false
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Single vip registry refresh property : null
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Force full registry fetch : false
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Application is null : false
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Registered Applications size is zero : true
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Application version is -1: true
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Getting all instance registry info from the eureka server
2020-02-03 09:16:13.932 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : The response status is 200
2020-02-03 09:16:13.935 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Starting heartbeat executor: renew interval is: 30
2020-02-03 09:16:13.937 INFO 9952 --- [ restartedMain] c.n.discovery.InstanceInfoReplicator : InstanceInfoReplicator onDemand update allowed rate per min is 4
2020-02-03 09:16:13.940 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1580706973939 with initial instances count: 1
2020-02-03 09:16:13.943 INFO 9952 --- [ restartedMain] o.s.c.n.e.s.EurekaServiceRegistry : Registering application CIRCULARS-MICROSERVICE with eureka with status UP
2020-02-03 09:16:13.944 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Saw local status change event StatusChangeEvent [timestamp=1580706973943, current=UP, previous=STARTING]
2020-02-03 09:16:13.947 INFO 9952 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient :
DiscoveryClient_CIRCULARS-MICROSERVICE/HQTPM00184606D.ADM.local:circulars-microservice:8081: registering service...
2020-02-03 09:16:14.002 INFO 9952 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient :
DiscoveryClient_CIRCULARS-MICROSERVICE/HQTPM00184606D.ADM.local:circulars-microservice:8081 - registration status: 204
2020-02-03 09:16:14.029 INFO 9952 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2020-02-03 09:16:14.031 INFO 9952 --- [ restartedMain] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8081
2020-02-03 09:16:14.266 INFO 9952 --- [ restartedMain] ae.gov.adm.CircularsMicroservice : Started
CircularsMicroservice in 10.925 seconds (JVM running for 11.768) done
2020-02-03 09:16:19.478 INFO 9952 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-02-03 09:16:19.479 INFO 9952 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-02-03 09:16:19.498 INFO 9952 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in
18 ms
Circular Microservice called.....Params are:1, false, 0
entity manager instantiated...
2020-02-03 09:16:19.829 WARN 9952 --- [nio-8081-exec-1] org.hibernate.orm.deprecation : HHH90000022: Hibernate's
legacy org.hibernate.Criteria API is deprecated; use the JPA
javax.persistence.criteria.CriteriaQuery instead
criteria: CriteriaImpl(ae.gov.adm.saeed.hibernate.entity.GmCirculars:this[][organizationId=1, active<>2 or active is null])
2020-02-03 09:16:19.973 WARN 9952 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 923, SQLState:
42000
2020-02-03 09:16:19.973 ERROR 9952 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00923: FROM keyword not
found where expected
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2292)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2050)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2012)
at org.hibernate.loader.Loader.doQuery(Loader.java:953)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2815)
at org.hibernate.loader.Loader.doList(Loader.java:2797)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2629)
at org.hibernate.loader.Loader.list(Loader.java:2624)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:109)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1859)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:370)
at ae.gov.adm.saeed.dao.impl.GmCircularsDaoImpl.find(GmCircularsDaoImpl.java:111)
at ae.gov.adm.saeed.dao.impl.GmCircularsDaoImpl$$FastClassBySpringCGLIB$$464553b0.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at ae.gov.adm.saeed.dao.impl.GmCircularsDaoImpl$$EnhancerBySpringCGLIB$$aedf9fbb.find()
at ae.gov.adm.saeed.service.CircularsService.fetchAllCircularsForOrganization(CircularsService.java:66)
at ae.gov.adm.CircularsMicroservice.getAllCircularsForOrganization(CircularsMicroservice.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:523)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java: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: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:1598)
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)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00923: FROM keyword not found where expected
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57)
... 83 more
try to check if the table "MU_GM_CIRCULARS" exists in the database (probably yes) and whether you have access to it (probably not).
Connect the database using the credentials your code is using. Try the following
select * from dba_tables where table_name = 'MU_GM_CIRCULARS';
If there are any records, it means table exists in the system.
Next try this
select * from all_tables where table_name = 'MU_GM_CIRCULARS';
This will show if user has access to the table. If the table appears to be in the result, then check the "owner" column and try to reach the table using the following format
select * from owner.table_name
Hope this will help
It is a configuration issue of the database. I was adding a config.xml file, which is NOT needed in Spring Boot. Rather, I added these values to my application.properties file, and then everything worked fine.
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#xxxxxxxxxxx
spring.datasource.username=xxxxx
spring.datasource.password=xxxxx
I recently upgraded a Spring Boot based application from Hibernate 4 to Hibernate 5. Since then I observe a class loading problem. Obviously, the hibernate classes and my domain class get loaded by two different class loaders. This only happens if I launch the application with Spring DevTools and Hibernate 5. The combinations DevTools/Hibernate 4, mvn spring-boot:run/Hibernate 5 work.
The problem can be reproduced with the following simple spring boot app (the full eclipse project is available here)
#Entity
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String firstName;
private String lastName;
public Employee() {
}
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Id #GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return id + ": " + lastName + ", " + firstName;
}
}
public class AppConfig {
#Autowired
private DataSource dataSource;
#SuppressWarnings("serial")
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan("problem.domain");
sessionFactory.setHibernateProperties(new Properties() {
{
setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyTenSevenDialect");
setProperty("hibernate.hbm2ddl.auto", "create-drop");
setProperty("hibernate.current_session_context_class", "thread");
}
});
return sessionFactory;
}
}
#Component
public class DatabaseInitializer implements ApplicationRunner {
#Autowired
private SessionFactory sessionFactory;
#Override
public void run(ApplicationArguments args) throws Exception {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Employee empl = new Employee("John", "Doe");
session.persist(empl);
tx.commit();
}
}
#SpringBootApplication
public class SpringBootMain {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootMain.class, args);
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>swt6.spring</groupId>
<artifactId>hibernate5-problem</artifactId>
<packaging>jar</packaging>
<version>1.0.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<hibernate.version>5.1.0.Final</hibernate.version>
<derby.version>10.12.1.1</derby.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Running this program with Spring DevTools results in the following error:
2016-02-15 18:30:48.315 INFO 13828 --- [ restartedMain] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#55ad1b60'
2016-02-15 18:30:48.509 INFO 13828 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2016-02-15 18:30:48.536 INFO 13828 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-02-15 18:30:48.582 ERROR 13828 --- [ restartedMain] o.h.p.access.spi.GetterMethodImpl : HHH000122: IllegalArgumentException in class: problem.domain.Employee, getter method of property: id
2016-02-15 18:30:48.583 ERROR 13828 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed
java.lang.IllegalStateException: Failed to execute ApplicationRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:800) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:787) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:777) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at problem.main.SpringBootMain.main(SpringBootMain.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_66]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_66]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_66]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.3.2.RELEASE.jar:1.3.2.RELEASE]
Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of problem.domain.Employee.id
at org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:64) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:223) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4633) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4344) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:226) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:499) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:99) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:778) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:751) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:756) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_66]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_66]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_66]
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:338) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at com.sun.proxy.$Proxy56.persist(Unknown Source) ~[na:na]
at problem.main.DatabaseInitializer.run(DatabaseInitializer.java:24) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:797) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
... 11 common frames omitted
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_66]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_66]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_66]
at org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:41) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
... 29 common frames omitted
2016-02-15 18:30:48.585 INFO 13828 --- [ restartedMain] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/D:/P20058/Documents/FH/Lehre/SWT6U/Uebungen/SpringWeb/hibernate5-problem/target/classes/]
2016-02-15 18:30:48.585 INFO 13828 --- [ restartedMain] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report enable debug logging (start with --debug)
2016-02-15 18:30:48.585 INFO 13828 --- [ restartedMain] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#63e38bca: startup date [Mon Feb 15 18:30:46 CET 2016]; root of context hierarchy
2016-02-15 18:30:48.587 INFO 13828 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2016-02-15 18:30:48.587 INFO 13828 --- [ restartedMain] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed drop of schema as part of SessionFactory shut-down'
2016-02-15 18:30:48.604 INFO 13828 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2016-02-15 18:30:48.604 INFO 13828 --- [ restartedMain] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed drop of schema as part of SessionFactory shut-down'
There is an open issue for supporting Hibernate 5 with Spring Boot here.
In your example, there are two classloaders :
The system classloader
Spring Boot DevTools classloader, supporting the restart feature
The default implement of Hibernate ClassLoaderService resolve classes by first looking in his own classloader, and then the spring classloader.
Your class are loaded by spring (with the restart classloader), given to hibernate through the persistent-unit, but hibernate reload this class with his ClassLoaderService, and find it in his own classloader (the system cl). There are two classes loaded, and the consequence is the error you saw.
Spring can be configured to load hibernate in the restart classloader, but i didn't success to isolate a set of libraries : adding only hibernate-* fail with errors from spring-orm or a EntityManager not visible from the proxybuilder.
A working workaround (but really ugly!) : add in META-INF/spring-devtools.properties
restart.include.all=.*
I suppose there is a better solution than this one