Detached entity passed to persist java spring - java

So i have a big error when trying to do an update method in my spring application ,the problem is regarding to the Caracter class as thats the one the seems to generate it. When i set my stuff in main and try to update an Anime object in the database the Caracter class gives me the errors presented below
the code
package com.site.anime.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Data
public class Caracter {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String image;
private String description;
private Double overall_mark;
#ManyToMany(cascade = { CascadeType.ALL })
private List<Anime> shows;
}
package com.site.anime.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Data
public class Anime {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String image;
private Integer no_episodes;
private String description;
private Double overall_score;
#ManyToMany(cascade = { CascadeType.ALL })
private List<Caracter> caracters;
#OneToMany(cascade = { CascadeType.ALL })
private List<Review> reviews;
#ManyToMany(cascade = { CascadeType.ALL })
private List<Category> categories;
}
package com.site.anime.service.impl;
import com.site.anime.model.Anime;
import com.site.anime.repository.RepositoryShow;
import com.site.anime.service.AnimeService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.lang.reflect.Field;
#Service
public class AnimeServiceImpl implements AnimeService {
private final RepositoryShow repositoryShow;
public AnimeServiceImpl(RepositoryShow repositoryShow) {
this.repositoryShow = repositoryShow;
}
#Override
public Anime findFirstByName(String name) {
return repositoryShow.findFirstByName(name);
}
#Override
#Transactional
public Anime updateAnime(Anime newShow) {
Anime anime=repositoryShow.findById(newShow.getId()).orElseThrow();
//System.out.println(anime.getCaracters().get(0).getName());
if(newShow.getName()!=null){
anime.setName(newShow.getName());
}
if(newShow.getImage()!=null){
anime.setImage(newShow.getImage());
}
if(newShow.getNo_episodes()!=null){
anime.setNo_episodes(newShow.getNo_episodes());
}
if(newShow.getDescription()!=null){
anime.setDescription(newShow.getDescription());
}
if(newShow.getCaracters()!=null){
anime.setCaracters(newShow.getCaracters());
}
if(newShow.getCategories()!=null){
anime.setCategories(newShow.getCategories());
}
return anime;
//anime=newShow;
// Field[] fields = anime.getClass().getDeclaredFields();
// Field[] fields1 = newShow.getClass().getDeclaredFields();
// for(int i=0;i<fields.length;i++){
// if(fields[i]!=fields1[i]){
// fields[i]=fields1[i];
// }
// }
//return null;
}
}
package com.site.anime;
import com.site.anime.model.*;
import com.site.anime.repository.*;
import com.site.anime.service.impl.AnimeServiceImpl;
import com.site.anime.service.impl.CaracterServiceImpl;
import com.site.anime.service.impl.UserServiceImpl;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
#EnableJpaRepositories
#SpringBootApplication
public class AnimeApplication {
public static void main(String[] args) {
SpringApplication.run(AnimeApplication.class, args);
}
#Bean
CommandLineRunner init(RepositoryShow repositoryShow, RepositoryCategory repositoryCategory,
RepositoryCaracter repositoryCaracter, RepositoryUser repositoryUser,
RepositorySuperUser repositorySuperUser, ProfileRepository profileRepository, AnimeServiceImpl animeService,
CaracterServiceImpl caracterService, UserServiceImpl userService){
return args -> {
List<Anime> shows=new LinkedList<>();
Caracter caracter=new Caracter(null,"Subaru","","",0.0,null);
List<Caracter> caracters=new LinkedList<>();
caracters.add(caracter);
Profile profile=new Profile(null,"","",18,"",null,null,null,null,null);
Utilizator user=new Utilizator(null);
user.setName("rusu");
//Review review=new Review(null,user,"",0);
Review review=new Review(null,"",2,null,null,null);
Review review1=new Review(null,"",5,null,null,null);
List<Review> reviews=new LinkedList<>();
review.setUser(user);
review1.setUser(user);
reviews.add(review);
reviews.add(review1);
//profile.setUser(user);
Anime show=new Anime(null,"ReZero Season 1","",25,"",0.0,null,reviews,null);
shows.add(show);
caracter.setShows(shows);
show.setCaracters(caracters);
review.setReviewed_show(show);
review1.setReviewed_show(show);
profile.setReviews(reviews);
user.setProfile(profile);
repositoryShow.save(show);
repositoryCaracter.save(caracter);
repositoryUser.save(user);
System.out.println(animeService.findFirstByName("ReZero Season 1").getName());
//System.out.println(repositoryUser.findFirstByName("rusu").getName());
Anime show1=new Anime(null,"ReZero Season 2","",25,"",0.0,null,reviews,null);
System.out.println(caracterService.findFirstByName("Subaru").getName());
System.out.println(userService.findFirstByName("rusu").getName());
//System.out.println(animeService.findFirstByName("ReZero Season 1"));
Utilizator user1=new Utilizator(null);
List<Review> reviews1=new LinkedList<>();
Review review2=new Review(null,"",2,null,null,null);
Profile profile1=new Profile(null,"","",18,"",null,null,null,null,null);
review2.setUser(user1);
review2.setReviewed_show(show);
reviews1.add(review2);
profile1.setReviews(reviews1);
user1.setProfile(profile1);
repositoryUser.save(user1);
show.setName("ReZero Season 2");
animeService.updateAnime(show);
userService.deleteUser(user1);
};
}
}
and the error
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:807) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:788) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) ~[spring-boot-2.4.3.jar:2.4.3]
at com.site.anime.AnimeApplication.main(AnimeApplication.java:23) ~[classes/:na]
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.site.anime.model.Caracter; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.site.anime.model.Caracter
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:297) ~[spring-orm-5.3.4.jar:5.3.4]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-5.3.4.jar:5.3.4]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:566) ~[spring-orm-5.3.4.jar:5.3.4]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.3.4.jar:5.3.4]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.4.jar:5.3.4]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.4.jar:5.3.4]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) ~[spring-tx-5.3.4.jar:5.3.4]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.4.jar:5.3.4]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.4.jar:5.3.4]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750) ~[spring-aop-5.3.4.jar:5.3.4]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692) ~[spring-aop-5.3.4.jar:5.3.4]
at com.site.anime.service.impl.AnimeServiceImpl$$EnhancerBySpringCGLIB$$3ebceda5.updateAnime(<generated>) ~[classes/:na]
at com.site.anime.AnimeApplication.lambda$init$0(AnimeApplication.java:91) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.3.jar:2.4.3]
... 5 common frames omitted
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.site.anime.model.Caracter
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:120) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:104) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:765) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:341) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:492) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:416) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:525) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:456) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:419) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:151) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:159) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:149) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:82) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:93) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1362) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.4.jar:5.3.4]
... 16 common frames omitted

I think that the issue here is, that you are replacing the characters collection with a new collection and the collection has different object than the persistence context, although it uses the same primary key. Since you are cascading changes, Hibernate tries to flush the changes and realizes that an entity for that primary key is already associated with the persistence context and fails to flush with the exception you are seeing. If you want to just apply the entity to the database, try to use entityManager.merge without loading the entity first. Alternatively, you could also try to apply the collections like this:
if (newShow.getCaracters()!=null) {
for (Character c : newShow.getCaracters()) {
anime.getCaracters().add(entityManager.getReference(Character.class, c.getId());
}
}
if (newShow.getCategories()!=null) {
for (Category c : newShow.getCategories()) {
anime.getCategories().add(entityManager.getReference(Category.class, c.getId());
}
}

Related

I'm trying to setup JPA for the first time with this test project. Ran into the following error. I wanted to bulid many cars is owned by one owner

Mainly I wanted to build a relationship of MANY TO ONE. The relationship is many cars are owned by one owner.
This is my error:
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: #OneToOne or #ManyToOne on com.javatech.crud.example.entity.Car.owners references an unknown entity: java.util.List
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[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 com.javatech.crud.example.SpringBootCrudManyToOneExampleApplication.main(SpringBootCrudManyToOneExampleApplication.java:10) ~[classes/:na]
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.javatech.crud.example.entity.Car.owners references an unknown entity: java.util.List
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:100) ~[hibernate-core-5.6.3.Final.jar:5.6.3.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processEndOfQueue(InFlightMetadataCollectorImpl.java:1750) ~[hibernate-core-5.6.3.Final.jar:5.6.3.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1694) ~[hibernate-core-5.6.3.Final.jar:5.6.3.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1623) ~[hibernate-core-5.6.3.Final.jar:5.6.3.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:295) ~[hibernate-core-5.6.3.Final.jar:5.6.3.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.3.Final.jar:5.6.3.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.3.Final.jar:5.6.3.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.14.jar:5.3.14]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.14.jar:5.3.14]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.14.jar:5.3.14]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.14.jar:5.3.14]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.14.jar:5.3.14]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.14.jar:5.3.14]
... 16 common frames omitted
This is application class of the project:
package com.javatech.crud.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootCrudManyToOneExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCrudManyToOneExampleApplication.class, args);
}
}
This are my car entity classes:
package com.javatech.crud.example.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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="Car_TBL")
public class Car {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String modelName;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "fk_owner_id")
private List<Owner> owners;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public List<Owner> getOwners() {
return owners;
}
public void setOwners(List<Owner> owners) {
this.owners = owners;
}
}
This is my Owner entity class:
package com.javatech.crud.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Owner_TBL")
public class Owner {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String location;
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 String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
This is Owner Repository interface:
package com.javatech.crud.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.javatech.crud.example.entity.Owner;
#Repository
public interface OwnerRepository extends JpaRepository<Owner, Integer> {
public List<Owner> findByName(String name);
}
This is the Car Repository interface:
package com.javatech.crud.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.javatech.crud.example.entity.Car;
#Repository
public interface CarRepository extends JpaRepository<Car, Integer> {
}
This is the Owner Controller Class:
package com.javatech.crud.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.javatech.crud.example.entity.Owner;
import com.javatech.crud.example.service.OwnerService;
#RestController
public class OwnerController {
#Autowired
private OwnerService service;
#PostMapping("/addcars")
public void addCars(#RequestBody Owner owner){
service.save(owner);
}
}
This is the Owner Service Class:
package com.javatech.crud.example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javatech.crud.example.entity.Owner;
import com.javatech.crud.example.repository.CarRepository;
import com.javatech.crud.example.repository.OwnerRepository;
#Service
public class OwnerService {
#Autowired
private CarRepository carrepository;
#Autowired
private OwnerRepository ownerrepository;
public void save(Owner owner) {
List<Owner> owners = ownerrepository.findByName(owner.getName());
if(owners.isEmpty()) {
ownerrepository.save(owner);
}
}
}
In the side of List, you have to use #OneToMany not #ManyToOne
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "fk_owner_id")
private List<Owner> owners;
Looking at the exception:
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.javatech.crud.example.entity.Car.owners references an unknown entity: java.util.List
It means, that it does not recognize the owners field as an entity. To correct it, please complete the relationship by adding:
#JoinColumn(name = "some FK column")
private Car car;
In the Owner class.
Also, in the class Car,
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "fk_owner_id")
private List<Owner> owners;
This does not seem correct. Probably you want to model the relationship "A car can have many owners". If yes, please correct it to:
#OneToMany(targetEntity = Car.class, cascade = CascadeType.ALL)
#JoinColumn(name = "fk_owner_id")
private List<Owner> owners;

Failed to run CommandLineRunner (Spring Boot)

Whenever I try to run my code I get this error here:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:809) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:790) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1313) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-2.4.4.jar:2.4.4]
at de.hdm_stuttgart.finance_manager.FinanceManagerApplication.main(FinanceManagerApplication.java:24) ~[classes/: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.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.4.4.jar:2.4.4]
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : de.hdm_stuttgart.finance_manager.model.Expenses.category -> de.hdm_stuttgart.finance_manager.model.Category; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : de.hdm_stuttgart.finance_manager.model.Expenses.category -> de.hdm_stuttgart.finance_manager.model.Category
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:371) ~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:235) ~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:566) ~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.3.5.jar:5.3.5]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.5.jar:5.3.5]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.5.jar:5.3.5]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) ~[spring-tx-5.3.5.jar:5.3.5]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.5.jar:5.3.5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.5.jar:5.3.5]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.5.jar:5.3.5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.5.jar:5.3.5]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.4.6.jar:2.4.6]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.5.jar:5.3.5]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.5.jar:5.3.5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.5.jar:5.3.5]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.5.jar:5.3.5]
at jdk.proxy4/jdk.proxy4.$Proxy82.save(Unknown Source) ~[na:na]
at de.hdm_stuttgart.finance_manager.FinanceManagerApplication.lambda$demo$0(FinanceManagerApplication.java:31) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:806) ~[spring-boot-2.4.4.jar:2.4.4]
... 10 common frames omitted
Caused by: java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : de.hdm_stuttgart.finance_manager.model.Expenses.category -> de.hdm_stuttgart.finance_manager.model.Category
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:151) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1366) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.5.jar:5.3.5]
... 26 common frames omitted
Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : de.hdm_stuttgart.finance_manager.model.Expenses.category -> de.hdm_stuttgart.finance_manager.model.Category
at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:379) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:167) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:159) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:149) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:82) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:93) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1362) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
... 35 common frames omitted
This is my start application:
package de.hdm_stuttgart.finance_manager;
import de.hdm_stuttgart.finance_manager.model.Category;
import de.hdm_stuttgart.finance_manager.model.Expense;
import de.hdm_stuttgart.finance_manager.model.PaymentMethod;
import de.hdm_stuttgart.finance_manager.repository.ExpenseRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.Date;
#SpringBootApplication
public class FinanceManagerApplication {
private static final Logger log = LoggerFactory.getLogger(FinanceManagerApplication.class);
public static void main(String[] args) {
SpringApplication.run(FinanceManagerApplication.class, args);
}
#Bean
public CommandLineRunner demo(ExpenseRepository repo) {
return (args) -> {
log.info("Creating expense entities...");
repo.save(new Expense(new Date(), 28.99, "Hai Vu", "Essen", new Category("Leisure"), PaymentMethod.CASH));
};
}
}
My friends has the exact same code but it works for them but not for me and we do not know what the reason is.
The configuration is all the same, but why is it failing to run the CommandLineRunner?
EDIT:
So something wrong is with my Expense class or ExpenseRepository, but I still don't know why.
With other repository it works and also I tried a new project with a PersonRepository. But always the ExpenseRepository fail.
I also renamed it but always get this Exception...
This is my Expense Model
package de.hdm_stuttgart.finance_manager.model;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
#Entity
public class Expense {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Temporal(TemporalType.DATE)
private Date date;
private BigDecimal amount;
private String receiver;
private String purpose;
#ManyToOne
private Category category;
#Enumerated(EnumType.STRING)
private PaymentMethod paymentMethod;
public Expense(){}
public Expense(Date date, BigDecimal amount, String receiver, String purpose, Category category, PaymentMethod paymentMethod) {
this.date = date;
this.amount = amount;
this.receiver = receiver;
this.purpose = purpose;
this.category = category;
this.paymentMethod = paymentMethod;
}
}
And my ExpenseRepository is just plain like this
package de.hdm_stuttgart.finance_manager.repository;
import de.hdm_stuttgart.finance_manager.model.Expense;
import org.springframework.data.repository.CrudRepository;
public interface ExpenseRepository extends CrudRepository<Expense, Long> {
}
Try removing the ExpenseRepository and start the app. If it works, then ExpenseRepository related package scanning or Entity associated to that Repository scanning is not loading properly.

getting ***BeanCreationException*** pls suggest a solution to solve this

My requirement is to insert the supplier along with catalogue and I only want to unidirectional mapping. Is there is anyway to resolve it with unidirectional only because I want to fetch catalogues from supplier(supplierId) and I am new to stackoverflow if there is any editing mistake please comment down, I will fix it.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'supplierRepository' defined in com.inventory.repository.SupplierRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.inventory.entities.Supplier, at table: catalog, for columns: [org.hibernate.mapping.Column(supplier)]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:342) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1697) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1442) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:624) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:612) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:898) ~[spring-context-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554) ~[spring-context-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405) [spring-boot-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at com.inventory.SpringBootInventoryAssignmentApplication.main(SpringBootInventoryAssignmentApplication.java:9) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_271]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_271]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_271]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_271]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.6.RELEASE.jar:2.3.6.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.inventory.entities.Supplier, at table: catalog, for columns: [org.hibernate.mapping.Column(supplier)]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330) ~[spring-beans-5.2.11.RELEASE.jar:5.2.11.RELEASE]
... 33 common frames omitted
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.inventory.entities.Supplier, at table: catalog, for columns: [org.hibernate.mapping.Column(supplier)]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:403) ~[spring-orm-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_271]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_271]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_271]
at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_271]
Caused by: org.hibernate.MappingException: Could not determine type for: com.inventory.entities.Supplier, at table: catalog, for columns: [org.hibernate.mapping.Column(supplier)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:499) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:466) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.hibernate.mapping.Property.isValid(Property.java:227) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.hibernate.mapping.RootClass.validate(RootClass.java:267) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:354) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1259) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.11.RELEASE.jar:5.2.11.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.11.RELEASE.jar:5.2.11.RELEASE]
... 4 common frames omitted
Entities
Catalog.java
package com.inventory.entities;
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 com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "catalog")
public class Catalog {
#Id
#Column(length = 50)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int skuCode;
#Column(length = 50)
private String skuName;
#Column(length = 50)
private String skuDesc;
#Column(length = 50)
private String bName;
#Column(length = 50)
private String bDesc;
#JsonManagedReference
#JsonIgnore
private Supplier supplier;// FK
public Catalog() {
}
public Catalog(String skuName, String skuDesc, String bName, String bDesc, Supplier supplier) {
this.skuName = skuName;
this.skuDesc = skuDesc;
this.bName = bName;
this.bDesc = bDesc;
this.supplier = supplier;
}
public int getSkuCode() {
return skuCode;
}
public String getSkuName() {
return skuName;
}
public void setSkuName(String skuName) {
this.skuName = skuName;
}
public String getSkuDesc() {
return skuDesc;
}
public void setSkuDesc(String skuDesc) {
this.skuDesc = skuDesc;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getbDesc() {
return bDesc;
}
public void setbDesc(String bDesc) {
this.bDesc = bDesc;
}
public Supplier getSupplier() {
return supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
#Override
public String toString() {
return "Catalog [skuCode=" + skuCode + ", skuName=" + skuName + ", skuDesc=" + skuDesc + ", bName=" + bName
+ ", bDesc=" + bDesc + ", supplier=" + supplier + "]";
}
}
Supplier.java
package com.inventory.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
#Entity
#Table(name = "supplier")
public class Supplier {
#Id
#Column(length = 50)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int supplierId;
#Column(length = 50)
private String supplierName;
#OneToMany(mappedBy = "supplier", fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
#JsonBackReference
private List<Catalog> catalogList;
public Supplier() {
this.catalogList = new ArrayList<Catalog>();
}
public Supplier(String supplierName) {
this.supplierName = supplierName;
this.catalogList = new ArrayList<Catalog>();
}
public int getSupplierId() {
return supplierId;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public List<Catalog> getCatalogList() {
return catalogList;
}
public void setCatalogList(List<Catalog> catalogList) {
this.catalogList = catalogList;
}
}
Service Classes
CatalogService
package com.inventory.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.inventory.entities.Catalog;
import com.inventory.repository.CatalogRepository;
import com.inventory.service.CatalogService;
#Service
public class CatalogServiceImpl implements CatalogService {
#Autowired
private CatalogRepository catalogRepository;
#Override
public Catalog getCatalogById(int id) {
return catalogRepository.findById(id).get();
}
#Override
public Catalog saveCatalog(Catalog catalog) {
return catalogRepository.save(catalog);
}
}
SupplierServiceImpl
package com.inventory.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.inventory.entities.Supplier;
import com.inventory.repository.SupplierRepository;
import com.inventory.service.SupplierService;
#Service
public class SupplierServiceImpl implements SupplierService {
#Autowired
private SupplierRepository supplierRepository;
#Override
public Supplier getSupplierById(int id) {
return supplierRepository.findById(id).get();
}
#Override
public Supplier insertSupplier(Supplier supplier) {
return supplierRepository.save(supplier);
}
}
I also want to know how to write search query for for item name in spring boot. Suppose, supplier A have Lays potato chips, banana chips, masala chips, coffee. I want to
search catalog items based on its supplierID and when I search for "chips" then it shows all types of chips supplier A have in catalog then how can I write such queries in CrudRepository/JpaRepository so that I can use it in service layer.
You should annotate with #ManyToOne and #JoinColumn.
#ManyToOne
#JoinColumn
private Supplier supplier;
Update (15/02/21)
As you added that you want an unidirectional relationship, this is the way, in the catalog class:
#Column
private int supplierId;
You can remove the supplier field or mark it as #Transient.
You must save the supplier, get its id (as it is generated by the database), and set it in your catalog.

Java Spring Jpa Embedded Entity PropertyNotFoundException Could not locate field name Issue

I am trying to build a multiple table query with JPA using the following information:
Cust Srch Entity
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
//#NamedQueries({
// #NamedQuery(
// name = "CustSearchDto.retrieveCustomerByTaxPayerId",
// query = "SELECT cs FROM CustSrchDto cs WHERE cs.taxPayerId = ?1 and cs.customerLifecycleCode = ?2 and cs.customerTypeCode = ?3"
// )
//})
#Entity(name = "CustSrchDto")
#Table(name = "CUST_SRCH",
schema = "SAMS"
)
#Embeddable
public class CustSrchDto implements Serializable {
private static final long serialVersionUID = 5572174433231867682L;
#Id
#Column(name = "SRCH_NM")
private String searchName;
#Id
#Column(name = "INDIV_FIRST_NM")
private String individualFirstName;
#Id
#Column(name = "INDIV_MIDL_NM")
private String individualMiddleName;
#Id
#Column(name = "CUST_ID")
private String customerId;
#Column(name = "TXPYR_ID")
private String taxPayerId;
#Column(name = "SRCH_POSTAL_CD")
private String searchPostalCode;
#Column(name = "SWB_ORG_CD")
private String schwabOrgCode;
#Column(name = "PHON_AREA_ID")
private String phoneAreaId;
#Column(name = "PHON_PRFX_ID")
private String phonePrefixId;
#Column(name = "PHON_LINE_ID")
private String phoneLineId;
#Column(name = "CUST_LFCYC_CD")
private String customerLifecycleCode;
#Column(name = "CUST_TYPE_CD")
private String customerTypeCode;
}
Note: That the commented out named query was used to make sure I got everything working for just the one table. And when I used that as the query on the single table it works.
Cust Icv Xref Entity
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Entity(name = "CustIcvXrefDto")
#Table(name = "CUST_ICV_XREF",
schema = "SAMS"
)
#Embeddable
public class CustIcvXrefDto implements Serializable {
private static final long serialVersionUID = -8276309395441323238L;
#Id
#Column(name = "CUST_ID1")
private String customerId;
#Id
#Column(name = "PROFL_ID")
private String profileId;
#Id
#Column(name = "PARTY_ID")
private String partyId;
#Column(name = "SYS_OF_REC_IND")
private String systemOfRecordIndividual;
#Column(name = "MIGRTN_STAT")
private String marginStatus;
#Column(name = "AUDIT_UPDT_USER_ID")
private String auditUpdateUserId;
#Column(name = "AUDIT_UPDT_TS")
private String auditUpdateTimeStamp;
}
The class I am trying to use as the combination of both of these with the query is:
Customer Search
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#NamedQueries({
#NamedQuery(
name = "CustomerSearchDto.retrieveCustomerByTaxPayerId",
query = "select xr, cs from CustSrchDto cs , CustIcvXrefDto xr where cs.customerId = xr.customerId and cs.taxPayerId = ?1 and cs.customerLifecycleCode = ?2 and cs.customerTypeCode = ?3"
)
})
#Entity(name = "CustomerSearchDto")
#Table(name = "CUST_SRCH",
schema = "SAMS"
)
public class CustomerSearchDto implements Serializable {
private static final long serialVersionUID = 4832171797332928024L;
#Id
#GeneratedValue
private Integer id;
#Embedded
private CustSrchDto custSrchDto;
#Embedded
private CustIcvXrefDto custIcvXrefDto;
}
For reference:
Application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
public class BrokeragePartyOnboradingApplication {
public static void main(String[] args) {
SpringApplication.run(BrokeragePartyOnboradingApplication.class, args);
}
}
Repository:
import com.schwab.brokerage.party.onborading.api.outbound.db2.models.CustomerSearchDto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface CustSearchConnector extends JpaRepository<CustomerSearchDto, Integer> {
List<CustomerSearchDto> retrieveCustomerByTaxPayerId(String taxPayerId,
String customerLifecycleCode,
String customerTypeCode);
}
The stack trace of the error on startup is:
2020-05-04 12:21:40.419 WARN 9952 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/schwab/cat/dynamicrouting/config/DataSourceAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.PropertyNotFoundException: Could not locate field name [customerId] on class [com.schwab.brokerage.party.onborading.api.outbound.db2.models.CustomerSearchDto]
2020-05-04 12:21:40.422 INFO 9952 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-05-04 12:21:40.438 INFO 9952 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-04 12:21:40.452 ERROR 9952 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/schwab/cat/dynamicrouting/config/DataSourceAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.PropertyNotFoundException: Could not locate field name [customerId] on class [com.schwab.brokerage.party.onborading.api.outbound.db2.models.CustomerSearchDto]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at com.schwab.brokerage.party.onborading.BrokeragePartyOnboradingApplication.main(BrokeragePartyOnboradingApplication.java:14) [main/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.PropertyNotFoundException: Could not locate field name [customerId] on class [com.schwab.brokerage.party.onborading.api.outbound.db2.models.CustomerSearchDto]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:403) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
... 16 common frames omitted
Caused by: org.hibernate.PropertyNotFoundException: Could not locate field name [customerId] on class [com.schwab.brokerage.party.onborading.api.outbound.db2.models.CustomerSearchDto]
at org.hibernate.internal.util.ReflectHelper.findField(ReflectHelper.java:371) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.property.access.internal.PropertyAccessFieldImpl.<init>(PropertyAccessFieldImpl.java:34) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.property.access.internal.PropertyAccessStrategyFieldImpl.buildPropertyAccess(PropertyAccessStrategyFieldImpl.java:26) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:330) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:64) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:136) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:601) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:125) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_251]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_251]
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:181) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:299) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1237) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
... 20 common frames omitted
I am thinking it might have something to do with how I am embedding the entity classes. The ultimate goal is to create a multiple table query with JPA and get the results back that I can act on.
I think problem is that you cannot have an #Id annotated field in an Embeddable (#Embeddable annotated classes, which are not entiities).
Thanks

Cannot Insert List of ItemDetail ie.List<ItemDetail> (OBJECT) into a MySQL DataBase Feild through Hibernate using SpringMVC

I'm trying to create a table named 'invoicedto' in which,I have a field consisting a list of ItemDetail (POJO Object).
I need clarification on following:
1.Can we Insert a List of Object in a field in MySQL database?
If possible then how to do? What should be my datatype of column in MYSQL?
2.If we cannot insert a list?Is there any other method to achieve this scenario?
If have attached my code below:
Controller:
#Controller
public class InvoiceController {
#Autowired
InvoiceService invoiceService;
public void setInvoiceService(InvoiceService invoiceService) {
this.invoiceService=invoiceService;
}
#RequestMapping("/invoice/add")
public ModelAndView addInvoice(){
Map<String,Object> businessDataMap=new HashMap<>();
ModelAndView modelAndView=new ModelAndView();
String invoiceNumber = invoiceService.generateInvoiceNumber();
businessDataMap.put("invoiceNumber", invoiceNumber);
modelAndView.addAllObjects(businessDataMap);
modelAndView.setViewName("add_invoice");
return modelAndView;
}
}
Service:
package com.company.greeninvoice.service;
import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.company.greeninvoice.dao.InvoiceDao;
import com.company.greeninvoice.dto.Customer;
import com.company.greeninvoice.dto.Invoice;
import com.company.greeninvoice.entity.ItemDetail;
#Service
public class InvoiceServiceImpl implements InvoiceService{
public static final String EMPTY_STRING = "";
public static final String INVOICE_CODE = "INV";
public static final String SEPERATOR = "-";
public static final String DEFAULT_INVOICE_NUMBER = "0000";
public static final String INVOICE_FORMATTER = "%04d";
#Autowired
InvoiceDao invoiceDao;
public void setInvoiceDao(InvoiceDao invoiceDao){
this.invoiceDao = invoiceDao;
}
#Transactional
#Override
public String generateInvoiceNumber() {
insertRecord();
String invoiceNumber = EMPTY_STRING;
return invoiceNumber;
}
private void insertRecord() {
Invoice invoice=new Invoice();
LocalDate todayDate=LocalDate.now();
String yearCode = String.valueOf(todayDate.getYear()%1000);
String monthCode = LocalDate.now().getMonth().name().substring(0, 3);
String invoiceNumber=INVOICE_CODE+SEPERATOR+yearCode+monthCode+SEPERATOR+"0001";
invoice.setInvoiceNumber(invoiceNumber);
Customer customer=new Customer();
customer.setCustomerName("VENKAT");
customer.setMale(true);
invoice.setCustomerDetails(customer);
invoice.setTotalAmount((float) 25.02);
invoice.setInvoiceDate(Date.valueOf(todayDate));
List<ItemDetail> itemdetailsList=new ArrayList<>();
ItemDetail itemDetail=new ItemDetail();
itemDetail.setSerialNumber("1");
itemDetail.setItemDescription("Pencil");
itemDetail.setItemQuantity(2);
itemDetail.setItemRate(25);
itemDetail.setAmount(50);
itemdetailsList.add(itemDetail);
invoice.setItemdetailsList( itemdetailsList);
invoiceDao.addInvoice(invoice);
}
}
DAO:
package com.company.greeninvoice.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.company.greeninvoice.dto.Invoice;
#Repository
public class InvoiceDaoImpl implements InvoiceDao{
private static final Logger logger =
LoggerFactory.getLogger(InvoiceDaoImpl.class);
#Autowired
SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
#Override
public void addInvoice(Invoice invoice) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(invoice);
logger.info("Invoice saved successfully, Invoice Details="+invoice);
}
}
Model:
1.InvoiceModel:[Should I use,ElementCollection Annotation?]
Problem:List<ItemDetail> not Inserted.
package com.company.greeninvoice.dto;
import java.io.Serializable;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CollectionTable;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.CollectionId;
import com.company.greeninvoice.entity.ItemDetail;
import lombok.Data;
import lombok.Setter;
#Data
#Entity
#Setter
#Table(name="invoiceDto")
public class Invoice implements Serializable{
#Id
private String invoiceNumber;
private Date invoiceDate;
private Customer customerDetails;
#ElementCollection
private List<ItemDetail> itemdetailsList;
private float totalAmount;
}
Entity POJO Class:
package com.company.greeninvoice.entity;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Data;
#Data
#Entity
public class ItemDetail implements Serializable{
#Id
private String serialNumber;
private String itemDescription;
private int itemQuantity;
private float itemRate;
private float amount;
}
Tomcat Console in Eclipse:
Hibernate: insert into invoiceDto (customerDetails, invoiceDate, totalAmount, invoiceNumber) values (?, ?, ?, ?)
Hibernate: insert into Invoice_itemdetailsList (Invoice_invoiceNumber, itemdetailsList) values (?, ?)
Jan 21, 2018 5:50:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/greeninvoice] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'itemdetailsList' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5094)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1311)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:555)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:478)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:272)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy26.generateInvoiceNumber(Unknown Source)
at com.company.greeninvoice.controller.InvoiceController.addInvoice(InvoiceController.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
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:52)
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:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Folder Structure of my project
InvoiceDto Table structure in MySQL
Since Invoice and ItemDetail are annoatated with #Entity,You should use JPA relationship annotations (which including #ManyToMany, #ManyToOne, #OneToMany, #OneToOne) instead of using #ElementCollection. I assume your invoice includes many items, So i would use #OneToMany annoation on List<ItemDetail> like this:
#OneToMany
private List<ItemDetail> itemdetailsList;
If you still want to use #ElementCollection on List<ItemDetail> you have to use #Embeddable annoation on ItemDetail
#Data
#Embeddable
public class ItemDetail implements Serializable{
#Id
private String serialNumber;
private String itemDescription;
private int itemQuantity;
private float itemRate;
private float amount;
}

Categories