Java Spring Null Pointer Exception when saving ManyToOne - java

Trying to save an object of type "Salary" which has ManyToOne relationships with "Role", "City", "SalarySite". It appears to be printing correctly with all the expected data but saving fails. Other similar questions all seem to be missing "#Autowired" but it is present in mine.
The "Dataloader" class, runs a "GoogleSearchScraper" class where we see the error.
City
package fyi.incomeoutcome.salarytaxspend.city;
import fyi.incomeoutcome.salarytaxspend.salary.Salary;
import javax.persistence.*;
import java.util.Set;
#Entity
public class City {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
private String country;
private String currency;
#OneToMany(mappedBy="city", cascade = CascadeType.ALL)
private Set<Salary> salaries;
protected City(){}
public City(String name, String country, String currency){
this.name = name;
this.country = country;
this.currency = currency;
}
public String getName(){ return this.name; }
public String getCountry(){ return this.country; }
public String toString(){
return String.format("City[id=%d, name='%s', country = '%s', currency= '%s']",
id, name, country, currency);
}
}
City Repository
package fyi.incomeoutcome.salarytaxspend.city;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;
#Repository
public interface CityRepository extends CrudRepository<City, Long> {
}
Role
package fyi.incomeoutcome.salarytaxspend.role;
import fyi.incomeoutcome.salarytaxspend.salary.Salary;
import javax.persistence.*;
import java.util.Set;
#Entity
public class Role {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String seniority;
private String roleName;
#OneToMany(mappedBy="role", cascade = CascadeType.ALL)
private Set<Salary> salaries;
protected Role(){}
public Role(String seniority,String roleName){
this.seniority = seniority;
this.roleName = roleName;
}
public String getSeniorityAndRole(){
if (this.seniority != ""){
return String.format("%s %s", this.seniority, this.roleName);
} else{
return roleName;
}
}
public String toString(){
return String.format("id=%d, %s %s", id, seniority, roleName);
}
}
Role Repository
package fyi.incomeoutcome.salarytaxspend.role;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;
#Repository
public interface RoleRepository extends CrudRepository<Role, Long> {
}
SalarySite
package fyi.incomeoutcome.salarytaxspend.salary.salarysite;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class SalarySite {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
private String searchUrl;
private String salaryElementClass;
protected SalarySite(){}
public SalarySite(String name, String searchUrl, String salaryElementClass){
this.name = name;
this.searchUrl = searchUrl;
this.salaryElementClass = salaryElementClass;
}
public String getName() {
return name;
}
public String toString(){
return String.format("%s %s %s", name, searchUrl, salaryElementClass);
}
public String getSearchUrl(){
return searchUrl;
}
public String getSalaryElementClass(){
return salaryElementClass;
}
}
SalarySiteRepo
package fyi.incomeoutcome.salarytaxspend.salary.salarysite;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;
#Repository
public interface SalarySiteRepository extends CrudRepository<SalarySite, Long> {
}
Salary
package fyi.incomeoutcome.salarytaxspend.salary;
import fyi.incomeoutcome.salarytaxspend.city.City;
import fyi.incomeoutcome.salarytaxspend.role.Role;
import fyi.incomeoutcome.salarytaxspend.salary.salarysite.SalarySite;
import javax.persistence.*;
#Entity
public class Salary {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private int compensation;
#ManyToOne(optional = false)
#JoinColumn(name = "role_id")
private Role role;
#ManyToOne(optional = false)
#JoinColumn(name = "city_id")
private City city;
#ManyToOne(optional = false)
#JoinColumn(name = "site_id")
private SalarySite site;
protected Salary(){}
public Salary(int compensation, Role role, City city, SalarySite site){
this.compensation = compensation;
this.role = role;
this.city = city;
this.site = site;
}
public int getCompensation(){
return this.compensation;
}
public String getCity(){
return city.getName();
}
public String getSeniorityAndRoleName(){
return role.getSeniorityAndRole();
}
public String toString(){
return String.format("Salary[id=%d, compensation=%d, city='%s', role='%s'",
id, compensation, city, role);
}
}
Salary Repository
import fyi.incomeoutcome.salarytaxspend.city.City;
import fyi.incomeoutcome.salarytaxspend.role.Role;
import fyi.incomeoutcome.salarytaxspend.salary.salarysite.SalarySite;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface SalaryRepository extends CrudRepository<Salary, Long> {
//List<Salary> findByLocation(String location);
Salary findById(long id);
boolean existsBySiteAndCityAndRole(SalarySite salarySite, City city, Role role);
}
Dataloader
package fyi.incomeoutcome.salarytaxspend.salary.service;
import fyi.incomeoutcome.salarytaxspend.city.City;
import fyi.incomeoutcome.salarytaxspend.city.CityRepository;
import fyi.incomeoutcome.salarytaxspend.role.RoleRepository;
import fyi.incomeoutcome.salarytaxspend.salary.Salary;
import fyi.incomeoutcome.salarytaxspend.salary.SalaryRepository;
import fyi.incomeoutcome.salarytaxspend.salary.salarysite.SalarySite;
import fyi.incomeoutcome.salarytaxspend.role.Role;
import fyi.incomeoutcome.salarytaxspend.salary.salarysite.SalarySiteRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
#Component
#Slf4j
public class DataLoader {
#Autowired
private SalaryRepository salaryRepository;
#Autowired
private SalarySiteRepository siteRepository;
#Autowired
private CityRepository cityRepository;
#Autowired
private RoleRepository roleRepository;
#PostConstruct
public void process() {
List<SalarySite> salarySiteList = new ArrayList<>();
siteRepository.findAll().forEach(salarySiteList::add);
List<Role> roleList = new ArrayList<>();
roleRepository.findAll().forEach(roleList::add);
List<City> cityList = new ArrayList();
cityRepository.findAll().forEach(cityList::add);
List<Salary> salaryList = new ArrayList<>();
salaryRepository.findAll().forEach(salaryList::add);
log.info("Entering Loop");
log.info("--------------------");
int numberOfSalaries = salaryList.size();
int numberOfRoles = roleList.size();
int numberOfSites = salarySiteList.size();
int numberOfCities = cityList.size();
log.info(String.format("salary list %d", numberOfSalaries));
log.info(String.format("role list %d", numberOfRoles));
log.info(String.format("site list %d", numberOfSites));
log.info(String.format("city list %d", numberOfCities));
for (SalarySite salarySite : salarySiteList){
for (City city: cityList){
for (Role role: roleList){
boolean foundSalary = salaryRepository.existsBySiteAndCityAndRole(salarySite, city, role);
if (foundSalary == true) {
log.debug("Found");
} else {
log.debug("Not Found, Scraping");
String roleTitle = role.getSeniorityAndRole();
String cityName = city.getName();
String searchUrl = salarySite.getSearchUrl();
String salaryElementClass = salarySite.getSalaryElementClass();
ScraperService siteScraper = new GoogleSearchScraper(role, city, salarySite);
siteScraper.executeScrape();
}
}
}
}
}
}
Google Search Scraper
package fyi.incomeoutcome.salarytaxspend.salary.service;
import fyi.incomeoutcome.salarytaxspend.city.City;
import fyi.incomeoutcome.salarytaxspend.role.Role;
import fyi.incomeoutcome.salarytaxspend.salary.Salary;
import fyi.incomeoutcome.salarytaxspend.salary.SalaryRepository;
import fyi.incomeoutcome.salarytaxspend.salary.salarysite.SalarySite;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
#Component
#Slf4j
public class GoogleSearchScraper implements ScraperService {
private Role role;
private City city;
private SalarySite site;
private String webPageUrl;
private int compensation;
#Autowired
SalaryRepository salaryRepo;
public GoogleSearchScraper(){}
public GoogleSearchScraper(Role role, City city, SalarySite site){
this.role = role;
this.city = city;
this.site = site;
}
#Override
public void executeScrape(){
int statusCodeFetchUrl = fetchWebpageUrl();
log.info(String.format("fetchWebPageUrl for %s : %d", toString(), statusCodeFetchUrl));
int parsePageStatusCode = parsePageForSalary();
log.info(String.format("parseUrl for salary %s : %d", toString(), parsePageStatusCode));
saveSalary();
}
#Override
public int fetchWebpageUrl(){
String title = role.getSeniorityAndRole();
title = title.replace(" ", "+");
String searchUrl = site.getSearchUrl();
String cityName = city.getName();;
String fullUrl = String.format("%s%s+%s", searchUrl, title, cityName);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(fullUrl))
.GET()
.build();
int statusCode = 0;
try{
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
statusCode = response.statusCode();
String jsonResultLink = new JSONObject(response.body())
.getJSONArray("items")
.getJSONObject(0)
.getString("link");
log.info(city + " " + role + " " + jsonResultLink);
this.webPageUrl = jsonResultLink;
return statusCode;
} catch(Exception e) {
log.error(e.toString());
return statusCode;
}
}
#Override
public int parsePageForSalary() {
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(this.webPageUrl))
.GET()
.build();
int statusCode = 0;
try{
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
statusCode = response.statusCode();
Document doc = Jsoup.parse(response.body());
Element salaryElement = doc.getElementsByClass(site.getSalaryElementClass()).first();
String salaryText = salaryElement.text();
char[] salaryChars = salaryText.toCharArray();
String nonDigitCharacters = "";
for (char c: salaryChars){
if (!Character.isDigit(c)){
salaryText = salaryText.replace(Character.toString(c),"");
nonDigitCharacters += c;
}
}
log.info(this.toString() + " removed " + nonDigitCharacters + " from salary " + salaryText);
this.compensation = Integer.parseInt(salaryText);
return statusCode;
} catch (Exception e){
log.error(e.toString());
return statusCode;
}
}
public void saveSalary(){
Salary scrapedSalary = new Salary(this.compensation, this.role, this.city, this.site);
log.info("saving " + scrapedSalary.toString());
salaryRepo.save(scrapedSalary);
}
#Override
public String getWebPageUrl() {
return webPageUrl;
}
#Override
public int getSalary() {
if (this.compensation == 0){
parsePageForSalary();
return this.compensation;
}
return this.compensation;
}
public String toString(){
return String.format("Scraper %s, %s, %s", role.getSeniorityAndRole(),
city.getName(), site.getName());
}
}
Error
2022-01-23 10:53:54.194 INFO 34291 --- [ main] f.i.s.s.service.GoogleSearchScraper : saving Salary[id=0, compensation=36149, city='City[id=1, name='Dublin', country = 'Ireland', currency= 'EUR']', role='id=1, Junior Software Developer'
2022-01-23 10:53:54.194 WARN 34291 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataLoader': Invocation of init method failed; nested exception is java.lang.NullPointerException
2022-01-23 10:53:54.195 INFO 34291 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-01-23 10:53:54.196 INFO 34291 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-01-23 10:53:54.210 INFO 34291 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2022-01-23 10:53:54.211 INFO 34291 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-01-23 10:53:54.222 INFO 34291 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-01-23 10:53:54.237 ERROR 34291 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataLoader': Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:160) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:440) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.2.jar:2.6.2]
at fyi.incomeoutcome.salarytaxspend.SalaryTaxSpendApplication.main(SalaryTaxSpendApplication.java:27) ~[classes/:na]
Caused by: java.lang.NullPointerException: null
at fyi.incomeoutcome.salarytaxspend.salary.service.GoogleSearchScraper.saveSalary(GoogleSearchScraper.java:119) ~[classes/:na]
at fyi.incomeoutcome.salarytaxspend.salary.service.GoogleSearchScraper.executeScrape(GoogleSearchScraper.java:48) ~[classes/:na]
at fyi.incomeoutcome.salarytaxspend.salary.service.DataLoader.process(DataLoader.java:78) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:389) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:333) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:157) ~[spring-beans-5.3.14.jar:5.3.14]
... 18 common frames omitted

Since you are creating an instance of GoogleSearchScraper yourself, fields will not be autowired by Spring. Therefore, salaryRepository is null.
You could inject the SalaryRepository instance yourself upon creation of GoogleSearchScraper like this:
ScraperService siteScraper = new GoogleSearchScraper(role, city, salarySite, salaryRepo);
siteScraper.executeScrape();
Of course you need to add SalaryRepository to the constructor parameter list and assign it.
Consider removing #Component from GoogleSearchScraper if you want to create instances yourself. You only need it when instances shall be managed by Spring.

Related

UnsatisfiedDependencyException error in creating bean name in REST API

**
2021-11-26 20:30:57.375 WARN 11700 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookRestController': Unsatisfied dependency expressed through field 'bookService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImpl': Unsatisfied dependency expressed through field 'bookService'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bookServiceImpl': Requested bean is currently in creation: Is there an unresolvable circular reference?
2021-11-26 20:30:57.376 INFO 11700 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-11-26 20:30:57.382 INFO 11700 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-11-26 20:30:57.393 INFO 11700 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-11-26 20:30:57.396 INFO 11700 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-11-26 20:30:57.410 INFO 11700 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-26 20:30:57.437 ERROR 11700 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter:
**
APPLICATION FAILED TO START
Description:
The dependencies of some of the beans in the application context form a cycle:
bookRestController (field private BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.Rest.BookRestController.bookService)
┌─────┐
| bookServiceImpl (field private BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.serviceImpl.BookServiceImpl.bookService)
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.*
BasicProjectApplication.java
```package BookAuthorManyToManyRelationship;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class BasicProjectApplication {
public static void main(String[] args) {
SpringApplication.run(BasicProjectApplication.class, args);
}
}```
**AuthorDAO.java**
```package BookAuthorManyToManyRelationship.dao;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface AuthorDAO {
public Author findById(int id);
public List<Book> findListOfBookWrittenByAuthor();
public void deleteById(int id);
public void save(Author author);
}```
**BookDAO.java**
```package BookAuthorManyToManyRelationship.dao;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface BookDAO {
public Book findById(int id);
public List<Author> findListOfAuthorWhoHasWrittenThisBook();
public void deleteById(int id);
public void save(Book book);
}```
**AuthorDAOImpl.java**
```package BookAuthorManyToManyRelationship.daoImpl;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import BookAuthorManyToManyRelationship.dao.AuthorDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
#Repository
public class AuthorDAOImpl implements AuthorDAO {
#Autowired
private EntityManager entityManager;
#Override
public Author findById(int id) {
Session session = entityManager.unwrap(Session.class);
Author author = session.get(Author.class, id);
return author;
}
#Override
public List<Book> findListOfBookWrittenByAuthor() {
Session session = entityManager.unwrap(Session.class);
Query<Book> theQuery = session.createQuery("from Book",Book.class);
List<Book> book = theQuery.getResultList();
return book;
}
#Override
public void deleteById(int id) {
Session session = entityManager.unwrap(Session.class);
Query theQuery = session.createQuery("delete from Author where author_id=:theid");
theQuery.setParameter("theid", id);
theQuery.executeUpdate();
}
#Override
public void save(Author author) {
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(author);
}
}```
**BookDAOImpl.java**
```package BookAuthorManyToManyRelationship.daoImpl;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import BookAuthorManyToManyRelationship.dao.BookDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
#Repository
public class BookDAOImpl implements BookDAO {
#Autowired
private EntityManager entityManager;
#Override
public Book findById(int id) {
Session session = entityManager.unwrap(Session.class);
Book b = session.get(Book.class, id);
return b;
}
#Override
public List<Author> findListOfAuthorWhoHasWrittenThisBook() {
Session session = entityManager.unwrap(Session.class);
Query<Author> q = session.createQuery("from Author",Author.class);
List<Author> author = q.getResultList();
return author;
}
#Override
public void deleteById(int id) {
Session session = entityManager.unwrap(Session.class);
Query q = session.createQuery("delete from Book where book_id:=theid");
q.setParameter("theid", id);
q.executeUpdate();
}
#Override
public void save(Book book) {
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(book);
}
}```
**Address.java**
```package BookAuthorManyToManyRelationship.entity;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
String street;
String city;
String country;
public Address(String street, String city, String country) {
super();
this.street = street;
this.city = city;
this.country = country;
}
public Address() {
super();
// TODO Auto-generated constructor stub
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}```
**Author.java**
```package BookAuthorManyToManyRelationship.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="author")
public class Author {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
String authorName;
Address address;
#ManyToMany(cascade = CascadeType.ALL)
List<Book> book;
public Author() {
super();
// TODO Auto-generated constructor stub
}
public Author(int id, String authorName,Address address,List<Book> book) {
super();
this.id = id;
this.authorName = authorName;
this.address = address;
this.book = book;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Book> getBook() {
return book;
}
public void setBook(List<Book> book) {
this.book = book;
}
}```
**Book.java**
```package BookAuthorManyToManyRelationship.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="book")
public class Book {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
String book_name;
String subject;
#ManyToMany(cascade = CascadeType.ALL)
List<Author> author;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(int id, String book_name, String subject, List<Author> author) {
super();
this.id = id;
this.book_name = book_name;
this.subject = subject;
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<Author> getAuthor() {
return author;
}
public void setAuthor(List<Author> author) {
this.author = author;
}
}```
**AuthorRestController**
```package BookAuthorManyToManyRelationship.Rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.AuthorService;
#RestController
#RequestMapping("/welcome")
public class AuthorRestController {
#Autowired
private AuthorService authorService;
#GetMapping("/author/{id}")
public Author getAuthorById(#PathVariable int id )
{
return authorService.findById(id);
}
#GetMapping("/book")
public List<Book> getBook()
{
return authorService.findListOfBookWrittenByAuthor();
}
#PostMapping("/saveAuthor")
public void setAuthor(#RequestBody Author author)
{
authorService.save(author);
}
}```
**BookRestController.java**
```package BookAuthorManyToManyRelationship.Rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.BookService;
#RestController
#RequestMapping("/abc")
public class BookRestController {
#Autowired
private BookService bookService;
#GetMapping("/book/{id}")
public Book getBookById(#PathVariable int id )
{
return bookService.findById(id);
}
#GetMapping("/author")
public List<Author> getAuthor()
{
return bookService.findListOfAuthorWhoHasWrittenThisBook();
}
#PostMapping("/saveBook")
public void setBook(#RequestBody Book book)
{
bookService.save(book);
}
}```
**AuthorService.java**
```package BookAuthorManyToManyRelationship.service;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface AuthorService {
public Author findById(int id);
public List<Book> findListOfBookWrittenByAuthor();
public void deleteById(int id);
public void save(Author author);
}```
**BookService.java**
```package BookAuthorManyToManyRelationship.service;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface BookService {
public Book findById(int id);
public List<Author> findListOfAuthorWhoHasWrittenThisBook();
public void deleteById(int id);
public void save(Book book);
}```
**AuthorServiceImpl.java**
```package BookAuthorManyToManyRelationship.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import BookAuthorManyToManyRelationship.dao.AuthorDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.AuthorService;
#Service
public class AuthorServiceImpl implements AuthorService {
#Autowired
private AuthorDAO authorDAO;
#Override
#Transactional
public Author findById(int id) {
return authorDAO.findById(id);
}
#Override
#Transactional
public List<Book> findListOfBookWrittenByAuthor() {
return authorDAO.findListOfBookWrittenByAuthor();
}
#Override
#Transactional
public void deleteById(int id) {
authorDAO.deleteById(id);
}
#Override
#Transactional
public void save(Author author) {
authorDAO.save(author);
}
}```
**BookServiceImpl.java**
```package BookAuthorManyToManyRelationship.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.BookService;
#Service
public class BookServiceImpl implements BookService {
#Autowired
private BookService bookService;
#Override
#Transactional
public Book findById(int id) {
return bookService.findById(id);
}
#Override
#Transactional
public List<Author> findListOfAuthorWhoHasWrittenThisBook() {
return bookService.findListOfAuthorWhoHasWrittenThisBook();
}
#Override
#Transactional
public void deleteById(int id) {
bookService.deleteById(id);
}
#Override
#Transactional
public void save(Book book) {
bookService.save(book);
}
}
```
here is cause of your problem
#Service
public class BookServiceImpl implements BookService {
#Autowired
private BookService bookService
I am not able to understand why do you have reference of BookService inside it's own implementation, my best guess you wanted to add BookDAO here.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schemaParser'

I am trying to save the data in the database[PostgresQL] using graphql with JPA, spring-boot. I have created the schema and created the resolver.
I have created the Repository for the same.
While running the main java class it shows the below error.
It shows the error in resolver like there is no root resolver for the query type query.
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.9.jar:5.3.9]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.9.jar:5.3.9]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.3.jar:2.5.3]
at com.example.demo.DemographqlApplication.main(DemographqlApplication.java:9) ~[main/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.coxautodev.graphql.tools.SchemaParser]: Factory method 'schemaParser' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaClassScannerError: No Root resolvers for query type 'Query' found! Provide one or more com.coxautodev.graphql.tools.GraphQLQueryResolver to the builder.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.9.jar:5.3.9]
... 18 common frames omitted
Caused by: com.coxautodev.graphql.tools.SchemaClassScannerError: No Root resolvers for query type 'Query' found! Provide one or more com.coxautodev.graphql.tools.GraphQLQueryResolver to the builder.
at com.coxautodev.graphql.tools.SchemaClassScanner$RootTypesHolder.createRootType(SchemaClassScanner.kt:424) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaClassScanner$RootTypesHolder.<init>(SchemaClassScanner.kt:405) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaClassScanner.scanForClasses(SchemaClassScanner.kt:78) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaParserBuilder.scan(SchemaParserBuilder.kt:151) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaParserBuilder.build(SchemaParserBuilder.kt:157) ~[graphql-java-tools-5.2.4.jar:na]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration.schemaParser(GraphQLJavaToolsAutoConfiguration.java:57) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration$$EnhancerBySpringCGLIB$$7201a319.CGLIB$schemaParser$2(<generated>) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration$$EnhancerBySpringCGLIB$$7201a319$$FastClassBySpringCGLIB$$52dead8e.invoke(<generated>) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.9.jar:5.3.9]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.9.jar:5.3.9]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration$$EnhancerBySpringCGLIB$$7201a319.schemaParser(<generated>) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.9.jar:5.3.9]
... 19 common frames omitted```
**Model/autor.java**
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "age")
private Integer age;
public Author() {
}
public Author(Long id) {
this.id = id;
}
public Author(String name, Integer age) {
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public void setAge(Integer age) {
this.age=age;
}
public Integer getAge() {
return age;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
**model/tutorial.java**
```#Entity
public class Tutorial {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "title", nullable = false)
private String title;
#Column(name = "description")
private String description;
#ManyToOne
#JoinColumn(name = "author_id", nullable = false, updatable = false)
private Author author;
public Tutorial() {
}
public Tutorial(String title, String description, Author author) {
this.title = title;
this.description = description;
this.author = author;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
#Override
public String toString() {
return "Tutorial [id=" + id + ", title=" + title + ", description=" + description + ", author=" + author + "]";
}
}```
**Author Repository**
```import org.springframework.data.jpa.repository.*;
import com.example.demo.model.Author;
public interface AuthorRepository extends JpaRepository<Author, Long>{
}```
**Tutorial repository**
```import com.example.demo.model.Tutorial;
import org.springframework.data.jpa.repository.*;
public interface TutorialRepository extends JpaRepository<Tutorial, Long> {}```
**Mutation resolver**
``` import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.demo.model.Author;
import com.example.demo.model.Tutorial;
import com.example.demo.repository.AuthorRepository;
import com.example.demo.repository.TutorialRepository;
//import graphql.kickstart.tools.GraphQLMutationResolver;
import javassist.NotFoundException;
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
#Component
public class Mutation implements GraphQLMutationResolver {
private AuthorRepository authorRepository;
private TutorialRepository tutorialRepository;
#Autowired
public Mutation(AuthorRepository authorRepository, TutorialRepository tutorialRepository) {
this.authorRepository = authorRepository;
this.tutorialRepository = tutorialRepository;
}
public Author createAuthor(String name, Integer age) {
Author author = new Author();
author.setName(name);
author.setAge(age);
authorRepository.save(author);
return author;
}
public Tutorial createTutorial(String title, String description, Long authorId) {
Tutorial tutorial = new Tutorial();
tutorial.setAuthor(new Author(authorId));
tutorial.setTitle(title);
tutorial.setDescription(description);
tutorialRepository.save(tutorial);
return tutorial;
}
public boolean deleteTutorial(Long id) {
tutorialRepository.deleteById(id);
return true;
}
public Tutorial updateTutorial(Long id, String title, String description) throws NotFoundException {
Optional<Tutorial> optTutorial = tutorialRepository.findById(id);
if (optTutorial.isPresent()) {
Tutorial tutorial = optTutorial.get();
if (title != null)
tutorial.setTitle(title);
if (description != null)
tutorial.setDescription(description);
tutorialRepository.save(tutorial);
return tutorial;
}
throw new NotFoundException("Not found Tutorial to update!");
}
}```
**Query-resolver**
``` import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.demo.model.Author;
import com.example.demo.model.Tutorial;
import com.example.demo.repository.AuthorRepository;
import com.example.demo.repository.TutorialRepository;
//import com.coxautodev.graphql.tools.GraphQLQueryResolver
import graphql.kickstart.tools.GraphQLQueryResolver;
#Component
public class Query implements GraphQLQueryResolver {
private AuthorRepository authorRepository;
private TutorialRepository tutorialRepository;
#Autowired
public Query(AuthorRepository authorRepository, TutorialRepository tutorialRepository) {
this.authorRepository = authorRepository;
this.tutorialRepository = tutorialRepository;
}
public Iterable<Author> findAllAuthors() {
return authorRepository.findAll();
}
public Iterable<Tutorial> findAllTutorials() {
return tutorialRepository.findAll();
}
public long countAuthors() {
return authorRepository.count();
}
public long countTutorials() {
return tutorialRepository.count();
}
}```
**Tutorial Resolver**
```import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.coxautodev.graphql.tools.GraphQLResolver;
import com.example.demo.model.Author;
import com.example.demo.model.Tutorial;
import com.example.demo.repository.AuthorRepository;
#Component
public class TutorialResolver implements GraphQLResolver<Tutorial> {
#Autowired
private AuthorRepository authorRepository;
public TutorialResolver(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public Author getAuthor(Tutorial tutorial) {
return authorRepository.findById(tutorial.getAuthor().getId()).orElseThrow(null);
}
}```
**application.properties**
spring.datasource.url=jdbc:postgresql://localhost:5432/spgraphql_demo
spring.datasource.username=login
spring.datasource.password=admin#123
spring.jpa.hibernate.ddl-auto=update
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.main.web-application-type=none

json parse error post data spring boot mysql

I have this problem in the back end when I post a data form from angular please someone help me I trie to solve this problem by object mapper but I don't understand well how can I do it correctly
the error is :
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of entity.Group (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{
"idGrp": 2,
"nomGroup": "intranet"
}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of entity.Group (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{
"idGrp": 2,
"nomGroup": "intranet"
}')
at [Source: (PushbackInputStream); line: 1, column: 236] (through reference chain: entity.Employe["group"])]*
this is my class Group
package entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="groups")
public class Group implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long idGrp;
private String NomGroup;
public Group()
{
}
public Group(Long id, String nomGroup) {
super();
this.idGrp = id;
NomGroup = nomGroup;
}
}
Im trying to post a data of employee which contain the data of entity group
class employee
package entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;
#Entity
public class Employe implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "myid")
#GenericGenerator(name = "myid", strategy = "entity.MyGenerator")
private Integer matricule;
private String nom;
private String prenom ;
private String nom_ar;
private String prenom_ar;
private int age;
private String description;
private String email;
private int codeP;
private int numTele;
private String adresse;
private String ville;
#JoinColumn(name="idGrp")
#ManyToOne(cascade = {CascadeType.ALL})
Group group;
public Employe(Integer matricule, String nom, String prenom, String nom_ar, String prenom_ar, int age,
String description, String email, int codeP, int numTele, String adresse, String ville, Group group) {
super();
this.matricule = matricule;
this.nom = nom;
this.prenom = prenom;
this.nom_ar = nom_ar;
this.prenom_ar = prenom_ar;
this.age = age;
this.description = description;
this.email = email;
this.codeP = codeP;
this.numTele = numTele;
this.adresse = adresse;
this.ville = ville;
}
public Employe(Integer matricule, String nom, String prenom, String nom_ar, String prenom_ar, int age,
String description, String email, int codeP, int numTele, String adresse, String ville) {
this.matricule = matricule;
this.nom = nom;
this.prenom = prenom;
this.nom_ar = nom_ar;
this.prenom_ar = prenom_ar;
this.age = age;
this.description = description;
this.email = email;
this.codeP = codeP;
this.numTele = numTele;
this.adresse = adresse;
this.ville = ville;
}
}
controller
#CrossOrigin(origins = "http://localhost:4200")
#PostMapping("addEmp")
public ResponseEntity<Employe> addEmp(#RequestBody Employe ep) throws JsonProcessingException
{
Employe p=this.servEmp.addEmp(ep);
return new ResponseEntity<>(p, HttpStatus.CREATED);
}
please help me how can I convert the json data to object I spend now two days In this error
I try to use commandRunner
#Bean
public CommandLineRunner run(ServiceEmp ServiceEmp) {
return args->{
Employe e=new Employe(0,"","","","",0,"","",0,0,"","");
ObjectMapper objectMapper=new ObjectMapper();
TypeReference<Employe> TypeReference =new TypeReference<Employe>() {};
InputStream InputStream=TypeReference.class.getResourceAsStream(objectMapper.writeValueAsString(ServiceEmp.addEmp(e)));
try {
e=objectMapper.readValue(InputStream,TypeReference);
ServiceEmp.addEmp(e);
System.out.print("saved");
}
catch(IOException a)
{
System.out.print("not saved"+a.getMessage());
}
output:
**Employe [nom=, prenom=, nom_ar=, prenom_ar=, matricule=0, age=0, description=, email=, codeP=0, numTele=0, adresse=, ville=]
[2m2021-09-25 20:40:39.966[0;39m [32m INFO[0;39m [35m10044[0;39m [2m---[0;39m [2m[ main][0;39m [36mConditionEvaluationReportLoggingListener[0;39m [2m:[0;39m
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2021-09-25 20:40:39.992[0;39m [31mERROR[0;39m [35m10044[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.boot.SpringApplication [0;39m [2m:[0;39m Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:794) ~[spring-boot-2.5.4.jar:2.5.4]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:775) ~[spring-boot-2.5.4.jar:2.5.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:345) ~[spring-boot-2.5.4.jar:2.5.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.4.jar:2.5.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.4.jar:2.5.4]
at cni.tn.CniApp.CniAppApplication.main(CniAppApplication.java:34) ~[classes/:na]
Caused by: java.lang.IllegalArgumentException: argument "src" is null
at com.fasterxml.jackson.databind.ObjectMapper._assertNotNull(ObjectMapper.java:4693) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3478) ~[jackson-databind-2.11.1.jar:2.11.1]
at cni.tn.CniApp.CniAppApplication.lambda$0(CniAppApplication.java:46) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:791) ~[spring-boot-2.5.4.jar:2.5.4]
... 5 common frames omitted**
The problem is the usage of constructors with parameters. Jackson can't map this by default. I think, there are two options:
Add the default constructor and all required getters and setters.
Add #JsonCreator to your paramized constructor.
For example:
public class Bean {
public int id;
public String name;
#JsonCreator
public Bean(
#JsonProperty("id") int id,
#JsonProperty("theName") String name) {
this.id = id;
this.name = name;
}
}
I am not sure, if you really need #JsonProperty for the parameters of the constructor, if you are using spring boot!

issue with #oneToMany bi-directional mapping in springboot

I am trying to retrieve data from 2 tables in MySql using spring boot and hibernate #OneToMany bi-directional mapping. But am getting this error among others:
No identifier specified for entity: com.dafe.spring.applogger.entity.Action
Please Check the error trace below:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-14 18:56:59.251 ERROR 8200 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.dafe.spring.applogger.entity.Action
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1771) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at com.dafe.spring.applogger.AppLoggerApplication.main(AppLoggerApplication.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_161]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.13.RELEASE.jar:2.1.13.RELEASE]
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.dafe.spring.applogger.entity.Action
at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:266) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:211) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:250) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:231) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:274) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1215) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1246) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1830) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
... 21 common frames omitted
the class the error is pointing to is below but I don't seem to know what the problem is. Find below is the com.dafe.spring.applogger.entity.Action class :
package com.dafe.spring.applogger.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
#Entity
#Table(name="action")
public class Action {
//declare & annotate your fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="time")
private Timestamp logTime;
#Column(name="type")
private String logType;
#Column(name="log_id")
private int userLogId;
#ManyToOne
#JoinColumn(name="log_id")
private UserLog userLog;
public Action(int id, Timestamp logTime, String logType, int userLogId, UserLog userLog) {
this.id = id;
this.logTime = logTime;
this.logType = logType;
this.userLogId = userLogId;
this.userLog = userLog;
}
//create and generate constructor
public Action() {
}
public Action(Timestamp logTime, String logType, int userLogId) {
this.logTime = logTime;
this.logType = logType;
this.userLogId = userLogId;
}
//generate getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timestamp getLogTime() {
return logTime;
}
public void setLogTime(Timestamp logTime) {
this.logTime = logTime;
}
public String getLogType() {
return logType;
}
public void setLogType(String logType) {
this.logType = logType;
}
public int getLogId() {
return userLogId;
}
public void setLogId(int logId) {
this.userLogId = logId;
}
public UserLog userLog() {
return userLog;
}
public void setLogs(UserLog userLog) {
this.userLog = userLog;
}
//generate toString
#Override
public String toString() {
return "Action [id=" + id + ", logTime=" + logTime + ", logType=" + logType + ", userLogId=" + userLogId + "]";
}
}
The action class is supposed to fetch data from database and has a foreign key relationship with class UserLog.
package com.dafe.spring.applogger.entity;
import java.util.ArrayList;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="log")
public class UserLog {
//define field
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="user_id")
private String userId;
#Column(name="session_id")
private String sessionId;
#OneToMany(mappedBy="log",cascade=CascadeType.ALL)
private ArrayList<Action>action;
//define constructors
public UserLog(String userId, String sessionId) {
this.userId = userId;
this.sessionId = sessionId;
}
//define getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public ArrayList<Action> getAction() {
return action;
}
public void setAction(ArrayList<Action> action) {
this.action = action;
}
//convenience method for Action
public void addAction(Action tempAction) {
if (action == null) {
action = new ArrayList<>();
}
action.add(tempAction);
}
//define toString
#Override
public String toString() {
return "Log [id=" + id + ", userId=" + userId + ", sessionId=" + sessionId + "]";
}
}
please help me figure out the problem and a possible solution. Thanks.
You have imported the Id from the wrong package.This error can be thrown when you import a different library for #Id than javax.persistance.Id ;
So change
import org.springframework.data.annotation.Id;
To
import javax.persistence.Id
Refer this thread
I think an issue is related to this mapping:
#OneToMany(mappedBy="log",cascade=CascadeType.ALL)
private ArrayList<Action>action;
mappedBy points to the name of the property on the 'owning' side. So in your case you should specify mappedBy="userLog" as it's defined in Action class
#ManyToOne
#JoinColumn(name="log_id")
private UserLog userLog;

Problem after adding (fetch = FetchType.EAGER) in many to many mapping in JPA/hiberante

I have Course.java class:
package com.ashwin.jpa.hiberante.jpaapp.entity;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name="course")
public class Course {
#Id
#GeneratedValue
private Long id;
#Column(name="name",nullable = false)
private String name;
#UpdateTimestamp
private LocalDateTime localDateTime;
#CreationTimestamp
private LocalDateTime createdDate;
//one to many
#OneToMany(mappedBy = "course",fetch = FetchType.EAGER)
private List<Review> reviewList=new ArrayList<>();
//many to many
#ManyToMany(mappedBy = "courses")
private List<Student> students=new ArrayList<>();
public Course(String name) {
this.name = name;
}
public Course(){
this.name=name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Course{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public List<Review> getReviewList() {
return reviewList;
}
public void setReview(Review review) {
this.reviewList.add(review);
}
public void removeReview(Review review) {
this.reviewList.remove(review);
}
public List<Student> getStudents() {
return students;
}
public void setStudent(Student student) {
this.students.add(student);
}
}
I have Student.java class
package com.ashwin.jpa.hiberante.jpaapp.entity;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Student {
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private String name;
//a student can have one passport
#OneToOne(fetch = FetchType.LAZY)
private Passport passport;
//many to many mapping
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name="STUDENT_COURSE",joinColumns = #JoinColumn(name="STUDENT_ID"),
inverseJoinColumns = #JoinColumn(name="COURSE_ID"))
private List<Course> courses=new ArrayList<>();
public Student(String name) {
this.name = name;
}
public Student(){
this.name=name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public Passport getPassport() {
return passport;
}
public void setPassport(Passport passport) {
this.passport = passport;
}
public List<Course> getCourses() {
return courses;
}
public void setCourse(Course course) {
this.courses.add(course);
}
}
The two classes are mapped by Many to Many annotation.Actually,at first my code at Student.java class was:
//many to many mapping
#ManyToMany
#JoinTable(name = "STUDENT_COURSE", joinColumns = #JoinColumn(name = "STUDENT_ID")
private List<Course> courses=new ArrayList<>();
At this stage the code was compiled successfully and i got the result using test case in StudentRepositoryTest.java as:
package com.ashwin.jpa.hiberante.jpaapp;
import com.ashwin.jpa.hiberante.jpaapp.entity.Course;
import com.ashwin.jpa.hiberante.jpaapp.entity.Passport;
import com.ashwin.jpa.hiberante.jpaapp.entity.Student;
import com.ashwin.jpa.hiberante.jpaapp.repository.CourseRepository;
import com.ashwin.jpa.hiberante.jpaapp.repository.StudentRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
#RunWith(SpringRunner.class)
#SpringBootTest
public class StudentRepositoryTest {
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Autowired
private StudentRepository studentRepository;
#Autowired
private EntityManager entityManager;
#Test
#Transactional
public void retrieveStudentAndCourses() {
//many to many mapping
Student student = entityManager.find(Student.class, 7 L);
logger.info("student is ->{}", student);
logger.info("student course is ->{}", student.getCourses());
}
}
The output was:
Hibernate: select student0_.id as id1_3_0_, student0_.name as name2_3_0_, student0_.passport_id as passport3_3_0_ from student student0_ where student0_.id=?
2019-08-01 20:58:38.410 TRACE 18608 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [7]
2019-08-01 20:58:38.464 TRACE 18608 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([name2_3_0_] : [VARCHAR]) - [Mike]
2019-08-01 20:58:38.466 TRACE 18608 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([passport3_3_0_] : [BIGINT]) - [6]
2019-08-01 20:58:38.507 TRACE 18608 --- [ main] org.hibernate.type.CollectionType : Created collection wrapper: [com.ashwin.jpa.hiberante.jpaapp.entity.Student.courses#7]
2019-08-01 20:58:38.560 INFO 18608 --- [ main] c.a.j.h.jpaapp.StudentRepositoryTest : student is ->Student{id=7, name='Mike'}
Hibernate: select courses0_.student_id as student_1_4_0_, courses0_.course_id as course_i2_4_0_, course1_.id as id1_0_1_, course1_.created_date as created_2_0_1_, course1_.local_date_time as local_da3_0_1_, course1_.name as name4_0_1_ from student_course courses0_ inner join course course1_ on courses0_.course_id=course1_.id where courses0_.student_id=?
Hibernate: select reviewlist0_.course_id as course_i4_2_0_, reviewlist0_.id as id1_2_0_, reviewlist0_.id as id1_2_1_, reviewlist0_.course_id as course_i4_2_1_, reviewlist0_.description as descript2_2_1_, reviewlist0_.rating as rating3_2_1_ from review reviewlist0_ where reviewlist0_.course_id=?
Hibernate: select reviewlist0_.course_id as course_i4_2_0_, reviewlist0_.id as id1_2_0_, reviewlist0_.id as id1_2_1_, reviewlist0_.course_id as course_i4_2_1_, reviewlist0_.description as descript2_2_1_, reviewlis
2019-08-01 20:58:38.561 INFO 18608 --- [ main] c.a.j.h.jpaapp.StudentRepositoryTest : student course is ->[Course{id=10001, name='JPA in 50steps'}, Course{id=10002, name='Spring in 50steps'}]
But when I add (fetch = FetchType.EAGER) like as:
//many to many mapping
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name="STUDENT_COURSE",joinColumns = #JoinColumn(name="STUDENT_ID"),
inverseJoinColumns = #JoinColumn(name="COURSE_ID"))
private List<Course> courses=new ArrayList<>();
I got the error as:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:
Invocation of init method failed; nested exception is
javax.persistence.PersistenceException: [Per
Caused by: org.hibernate.loader.MultipleBagFetchException: cannot
simultaneously fetch multiple bags:
[com.ashwin.jpa.hiberante.jpaapp.entity.Student.courses,
com.ashwin.jpa.hiberante.jpaapp.entity.Course.reviewList]

Categories

Resources