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;
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());
}
}
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
Hi~ I was in trouble using Spring Data JPA.
this trouble github url : https://github.com/moregorenine/toyproject/tree/jpa_self_join_save/tree-structure-ztree
Development environment
spring-boot-starter-parent : 2.0.6.RELEASE + JPA + H2
spring data jpa reference : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
Everything works fine. Except one.
don't work parameter type : [small letter][capital letter]... ex) tId
if change {tId} to {tempId} is good work!!! but I want use {tId}
ZTreeService.java
good work! no problem exmaple!!!
(O) zTrees = zTreeRepository.findAllByOrderById();
(O) zTrees = zTreeRepository.findAllByOrderByName();
(O) zTrees = zTreeRepository.findAllByOrderByIsParent();
don't work! only this type exmaple!!! why~
(X) zTrees = zTreeRepository.findAllByOrderByTId();
tId type parameter possible create, insert from spring data JPA.
But Does 'OrderBy' method not support [small letter][capital letter] type parameter?
ZTree.java
package com.github.moregorenine.ztree.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import javax.validation.constraints.NotBlank;
#Entity
public class ZTree {
#Id
#GeneratedValue
private Long id; // 본인 id
private String tId; // Ztree 내장 id
#Transient
private String parentTId; // Ztree 내장 pId
#Transient
private Long level; // lvl : 같은 그룹내 계층
#NotBlank(message = "Name을 작성해주세요.")
private String name;
private String isParent;
private String url; // 메뉴에 연결할 url
private String useYn; // 메뉴 사용여부
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="pId")
private ZTree parent;
#OneToMany(mappedBy="parent", cascade={CascadeType.ALL})
private Set<ZTree> children = new HashSet<ZTree>();
}
ZTreeService.java
#Service
public class ZTreeService {
#Autowired
private ZTreeRepository zTreeRepository;
public List<ZTree> getAllZTrees() {
List<ZTree> zTrees = new ArrayList<>();
zTrees = zTreeRepository.findAllByOrderByTId();
return zTrees;
}
}
H2 Database
enter image description here
build failure message
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'ZTreeController': Unsatisfied dependency expressed through field 'zTreeService';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'ZTreeService': Unsatisfied dependency expressed through field 'zTreeRepository';
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'ZTreeRepository': Invocation of init method failed;
nested exception is java.lang.IllegalArgumentException:
Failed to create query for method public abstract java.util.List com.github.moregorenine.ztree.repository.ZTreeRepository.findAllByOrderByTId()! Unable to locate Attribute with the the given name [TId] on this ManagedType [com.github.moregorenine.ztree.domain.ZTree]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at com.github.moregorenine.TreeStructureZtreeApplication.main(TreeStructureZtreeApplication.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_152]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_152]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_152]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_152]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.6.RELEASE.jar:2.0.6.RELEASE]
I Use 'Sort' instead of 'OrderByTid'
zTrees = zTreeRepository.findAll(new Sort(Sort.Direction.ASC, "tId"));
I am storing one class as serialize object in Database in JPA.
Now I am going to fetch that data using serialize object in where clause.
Below is my serialize object class
`
public class Candidates implements Serializable{
private static final long serialVersionUID = -6852589184246588241L;
Long id;
String firstname;
String lastname;
String email;
String address;
String phone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
`
And below is entity class where I'm storing serialize obejct
`
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.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.rms.vo.Candidates;
import lombok.Data;
#Entity
#Table(name = "candidate")
#Data
public class Candidate extends Auditable implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "candidate_sequence")
#SequenceGenerator(name = "candidate_sequence", sequenceName = "candidate_sequence", allocationSize = 50)
#Column(name = "candidate_id", updatable = false, nullable = false)
private Long id;
#ManyToOne
#JoinColumn(name="userId")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Lob
#Column(name = "resume")
private Serializable resume;
public Candidates getResume() {
return (Candidates) resume;
}
public void setResume(Candidates resume) {
this.resume = resume;
}
}
`
and I m using below method to fetch data but its giving kindly help me to solve this issue
`
#Query("from Candidate where resume.firstname='Mujahid' or resume.firstname='MUJAHID' ")
public List<Candidate> getCandidateListByName();
'
I m getting below error
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
24-11-2018 10:40:58.152 [restartedMain] ERROR o.s.boot.SpringApplication.reportFailure - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'candidateRestController': Unsatisfied dependency expressed through field 'candidateService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'candidateService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'candidateRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.rms.repository.CandidateRepository.getCandidateListByName()!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234)
at com.rms.RMSMain.main(RMSMain.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'candidateService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'candidateRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.rms.repository.CandidateRepository.getCandidateListByName()!
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'candidateRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.rms.repository.CandidateRepository.getCandidateListByName()!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:513)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:484)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:618)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:177)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
... 35 common frames omitted
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.rms.repository.CandidateRepository.getCandidateListByName()!
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:63)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:139)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:546)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:548)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:538)
at java.util.Optional.map(Optional.java:215)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:538)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:317)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:287)
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141)
at org.springframework.data.util.Lazy.get(Lazy.java:63)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:290)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
... 47 common frames omitted
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: firstname of: com.rms.entity.Candidate [from com.rms.entity.Candidate where resume.firstname='Mujahid' or resume.firstname='MUJAHID' ]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
at com.sun.proxy.$Proxy141.createQuery(Unknown Source)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
... 76 common frames omitted
Caused by: org.hibernate.QueryException: could not resolve property: firstname of: com.rms.entity.Candidate [from com.rms.entity.Candidate where resume.firstname='Mujahid' or resume.firstname='MUJAHID' ]
at org.hibernate.QueryException.generateQueryException(QueryException.java:120)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:217)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
... 84 common frames omitted
Caused by: org.hibernate.QueryException: could not resolve property: firstname of: com.rms.entity.Candidate
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:71)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:65)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1859)
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:393)
at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:512)
at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:687)
at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:270)
at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:210)
at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:1040)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1290)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4717)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4185)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2138)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2088)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:815)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:609)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
... 90 common frames omitted