Class loading error with Spring Boot and Hibernate 5 - java

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

Related

springBoot and hibernate 404 not found

I train with springboot and a mariadb database. When I test for data recovery, I get this message in postman:
{
"timestamp": "2022-03-03T13:53:18.609+00:00",
"status": 404,
"error": "Not Found",
"path": "/user/all"
}
. I tried several tutorials in copy paste and I always have the same message. I will also put the message that is in the console. Thank you in advance for your help.
controller
package controller;
import model.Users;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import service.UsersService;
import java.util.List;
#RestController
#RequestMapping("/user")
public class UsersController {
private UsersService usersService;
public UsersController(UsersService usersService) {
this.usersService = usersService;
}
#GetMapping("/all")
public ResponseEntity<List<Users>> getUsers() {
List<Users> users = usersService.getUsers();
return new ResponseEntity<>(users, HttpStatus.OK);
}
}
Service
package service;
import model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.UsersRepository;
import java.util.List;
#Service
public class UsersService {
private UsersRepository usersRepository;
#Autowired
public UsersService(UsersRepository usersRepository) {
this.usersRepository = usersRepository;
}
public List<Users> saveUsers(List<Users>users){
return usersRepository.saveAll(users);
}
public Users saveUsers(Users users){
return usersRepository.save(users);
}
public List<Users> getUsers(){
return usersRepository.findAll();
}
public Users getUserById(int id_user){
return usersRepository.findById(id_user).orElse(null);
}
}
Respository
package repository;
import model.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
}
Model
package model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id_user;
#Column(name="lastname")
private String lastname;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Column(name="phone")
private String phone;
#Column(name="adress")
private String adress;
#Column(name="city")
private String city;
#Column(name="country")
private String country;
}
Application properties
spring.jpa.hibernate.ddl-auto = update
spring.datasource.url = jdbc:mysql://localhost:3306/database
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect
Console
2022-03-03 14:52:57.479 INFO 24188 --- [ main] c.p.database.databaseApplication : No active profile set, falling back to 1 default profile: "default"
2022-03-03 14:52:58.412 INFO 24188 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-03-03 14:52:58.435 INFO 24188 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8 ms. Found 0 JPA repository interfaces.
2022-03-03 14:52:59.190 INFO 24188 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-03-03 14:52:59.204 INFO 24188 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-03-03 14:52:59.204 INFO 24188 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.58]
2022-03-03 14:52:59.370 INFO 24188 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-03-03 14:52:59.370 INFO 24188 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1816 ms
2022-03-03 14:52:59.627 INFO 24188 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-03-03 14:52:59.696 INFO 24188 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.5.Final
2022-03-03 14:52:59.892 INFO 24188 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-03-03 14:53:00.046 INFO 24188 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-03-03 14:53:00.252 INFO 24188 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-03-03 14:53:00.272 INFO 24188 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2022-03-03 14:53:00.652 INFO 24188 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-03-03 14:53:00.666 INFO 24188 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-03-03 14:53:00.722 WARN 24188 --- [ main] 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-03-03 14:53:01.296 INFO 24188 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-03 14:53:01.317 INFO 24188 --- [ main] c.p.database.databaseApplication : Started dataBaseApplication in 4.589 seconds (JVM running for 5.786)
2022-03-03 14:53:18.493 INFO 24188 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-03-03 14:53:18.493 INFO 24188 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-03-03 14:53:18.495 INFO 24188 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Every thing on the controller class is implemented properly and there is definitely no need for other layers implementation to share, you probably use SpringBootServletInitializer, in the main class add the #EnableWebMvc annotation and override SpringApplicationBuilder method as
#SpringBootApplication
#EnableWebMvc
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Otherwise if you use SpringApplication to sun the project make sure the main class annotated with #SpringBootApplication and be some thing like
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And final thing check the presence of spring boot starter web dependency in you pom file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
If you do not use spring boot parent do not forget to add the proper version to web starter artifact.

sessionRepository in com.sparsh.conferencedemo.controllers.SessionController required a bean of type that could not be found

I was trying to create a simple CRUD spring boot application after watching an online course. But when i run the application it shown an error "Field speakerRepository in com.sparsh.conferencedemo.controllers.SpeakerController required a bean of type 'com.sparsh.conferencedemo.repositories.SpeakerRepository' that could not be found." I don't understand what I am doing wrong. Also I am new to the spring boot. So any help please. I am posting my code below.
This is my SessionController
package com.sparsh.conferencedemo.controllers;
import com.sparsh.conferencedemo.models.Session;
import com.sparsh.conferencedemo.repositories.SessionRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/api/v1/sessions")
public class SessionController {
#Autowired
private SessionRepository sessionRepository;
#GetMapping
private List<Session> list(){
return sessionRepository.findAll();
}
#GetMapping
#RequestMapping("{id}")
private Session get(#PathVariable Long id){
return sessionRepository.getOne(id);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public Session create(#RequestBody final Session session){
return sessionRepository.saveAndFlush(session);
}
#RequestMapping(value="{id}", method = RequestMethod.DELETE)
public void delete(#PathVariable Long id){
sessionRepository.
}
#RequestMapping(value="{id}", method = RequestMethod.PUT)
public Session update(#PathVariable Long id, #RequestBody Session session){
Session existingSesseion=sessionRepository.getOne(id);
BeanUtils.copyProperties(session, existingSesseion, "session_id");
return sessionRepository.saveAndFlush(existingSesseion);
}
}
This is my SessionRepository interface
package com.sparsh.conferencedemo.repositories;
import com.sparsh.conferencedemo.models.Session;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SessionRepository extends JpaRepository<Session, Long> {
}
This is my pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sparsh</groupId>
<artifactId>conference-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>conference-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This is my Model for Session
package com.sparsh.conferencedemo.models;
import javax.persistence.*;
import java.util.List;
#Entity(name="sessions")
public class Session {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long session_id;
private String session_name;
private String session_description;
private String session_length;
#ManyToMany
#JoinTable(
name="session_speakers",
joinColumns = #JoinColumn(name = "session_id"),
inverseJoinColumns = #JoinColumn(name = "speaker_id")
)
private List<Speaker> speakers;
public Session(){
}
public List<Speaker> getSpeakers() {
return speakers;
}
public void setSpeakers(List<Speaker> speakers) {
this.speakers = speakers;
}
public Long getSession_id() {
return session_id;
}
public void setSession_id(Long session_id) {
this.session_id = session_id;
}
public String getSession_name() {
return session_name;
}
public void setSession_name(String session_name) {
this.session_name = session_name;
}
public String getSession_description() {
return session_description;
}
public void setSession_description(String session_description) {
this.session_description = session_description;
}
public String getSession_length() {
return session_length;
}
public void setSession_length(String session_length) {
this.session_length = session_length;
}
}
This is my main Application Class
package com.sparsh.conferencedemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ConferenceDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ConferenceDemoApplication.class, args);
}
}
These are the modules I am using in IntelliJ its an image link
https://imgur.com/a/riTdeot
These are the error I am getting in the console
:: Spring Boot :: (v2.2.6.RELEASE)
2020-04-29 12:44:29.844 INFO 10572 --- [ main] c.s.c.ConferenceDemoApplication : Starting ConferenceDemoApplication on DESKTOP-JBQF1EV with PID 10572 (C:\Users\spars\OneDrive\Desktop\conference-demo\target\classes started by spars in C:\Users\spars\OneDrive\Desktop\conference-demo)
2020-04-29 12:44:29.859 INFO 10572 --- [ main] c.s.c.ConferenceDemoApplication : No active profile set, falling back to default profiles: default
2020-04-29 12:44:38.081 INFO 10572 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-04-29 12:44:38.174 INFO 10572 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-04-29 12:44:38.175 INFO 10572 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33]
2020-04-29 12:44:38.582 INFO 10572 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-04-29 12:44:38.582 INFO 10572 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 8561 ms
2020-04-29 12:44:39.083 WARN 10572 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionController': Unsatisfied dependency expressed through field 'sessionRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sparsh.conferencedemo.repositories.SessionRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2020-04-29 12:44:39.090 INFO 10572 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-04-29 12:44:39.647 INFO 10572 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-04-29 12:44:40.370 ERROR 10572 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field sessionRepository in com.sparsh.conferencedemo.controllers.SessionController required a bean of type 'com.sparsh.conferencedemo.repositories.SessionRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.sparsh.conferencedemo.repositories.SessionRepository' in your configuration.
Process finished with exit code 1
Looks like you have run into the same issue that I have following Dan Bunker's spring boot Pluralsight course?
Looks like the course is a little out of date now and the latest version of spring boot doesn't appear to work with the project setup. Specifically I think it's a problem with how we have defined the JpaRespositories such that they cannot be auto wired.
Obviously if we are both following a beginners course it's a little tricky to establish the root cause.
I downgraded my project to 2.1.9.RELEASE in pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
And it worked! Good luck.

ERROR 9952 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00923: FROM keyword not found where expected

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

Unable to parse xml using XStreamMarshaller with spring batch + spring boot

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;
}

Field itemRepository in HomePageController required a bean of type ItemRepository that could not be found

I'm new to spring boot and have been trying to make simple REST web application.
I followed steps as shown in different guides but i still get the same problem when i try to run application.
This is the output i see everytime i try to run code
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.3.RELEASE)
2018-07-06 10:47:44.768 INFO 11172 --- [ main] App.App : Starting App on DESKTOP-OTCRH25 with PID 11172 (started by EhabArman-Notebook in E:\java workplace\eclipse-workplace\full)
2018-07-06 10:47:44.784 INFO 11172 --- [ main] App.App : No active profile set, falling back to default profiles: default
2018-07-06 10:47:44.925 INFO 11172 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#75c072cb: startup date [Fri Jul 06 10:47:44 EEST 2018]; root of context hierarchy
2018-07-06 10:47:46.785 INFO 11172 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-07-06 10:47:46.816 INFO 11172 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-07-06 10:47:46.816 INFO 11172 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-07-06 10:47:46.840 INFO 11172 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_171\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_171/bin/server;C:/Program Files/Java/jre1.8.0_171/bin;C:/Program Files/Java/jre1.8.0_171/lib/amd64;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.8.0_171\bin;C:\Program Files\Apache Software Foundation\apache-maven-3.5.4\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\PostgreSQL\10\lib;C:\Program Files\PostgreSQL\10\bin;C:\Program Files\apache-log4j-2.11.0-bin\log4j-api-2.11.0.jar;C:\Program Files\apache-log4j-2.11.0-bin\log4j-corei-2.11.0.jar;C:\Program Files\Git\cmd;C:\Program Files\MySQL\MySQL Shell 8.0\bin;C:\Program Files\MySQL\MySQL Server 8.0\bin;;C:\Program Files\Microsoft VS Code\bin;C:\Users\EhabArman-Notebook\Desktop;;.]
2018-07-06 10:47:46.985 INFO 11172 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-07-06 10:47:46.985 INFO 11172 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2060 ms
2018-07-06 10:47:47.172 INFO 11172 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-07-06 10:47:47.177 INFO 11172 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-06 10:47:47.178 INFO 11172 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-06 10:47:47.179 INFO 11172 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-06 10:47:47.179 INFO 11172 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-06 10:47:47.221 WARN 11172 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homePage': Unsatisfied dependency expressed through field 'itemRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'App.components.repository.ItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-07-06 10:47:47.224 INFO 11172 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-07-06 10:47:47.247 INFO 11172 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-07-06 10:47:47.390 ERROR 11172 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field itemRepository in App.components.controller.HomePage required a bean of type 'App.components.repository.ItemRepository' that could not be found.
Action:
Consider defining a bean of type 'App.components.repository.ItemRepository' in your configuration.
Here is 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>Test</groupId>
<artifactId>Full</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
</project>
my classes and hierarchy
App Class:
package App;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
package App.components.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import App.components.repository.*;
HomePage class:
import App.components.repository.*;
#Controller
public class HomePage {
#Autowired
private ItemRepository itemRepository;
#RequestMapping("/homepage")
public String getHomePage() {
return "homepage/homepage.html";
}
}
ItemRepository
package App.components.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import App.components.model.Item;
#Repository
public interface ItemRepository extends CrudRepository<Item, Long>{
}
Item class:
package App.components.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "item")
public class Item {
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "quantity")
private int quantity;
#Column(name = "price")
private int price;
public Item() {}
public Item(String name,int quantity ,int price) {
this.name = name;
this.quantity = quantity;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString() {
return "[" + id + " " + name + " " + price + " " + quantity +"]";
}
}
Change spring-data-jpa to spring-boot-starter-data-jpa and remove hibernate dependency. It comes with starter.
In main class use #SpringBootApplication.
Not Sure if you are implementing ItemRepository interface anywhere. Please implement it and remove the #Repository from below code and place it to your implemented class.
#Repository
public interface ItemRepository extends CrudRepository<Item, Long>{
}
And Please change CrudRepository<Item, Long> to CrudRepository<Item, int>
Hope it will fix the issue.

Categories