I trying to implement a database with a many-to-many relationship.The database has been built, now we need queries to it. I'm using this article as an example: https://www.bezkoder.com/jpa-many-to-many/. When I create custom finder in Repository - server crushes at running.
I have two Entity: MassageEntity and RstringsEntity. I'm trying to create a method List<MasageEntity> findMasageEntitiesByRstringsEntitiesId(Long string_id);. Without that method server starts.
This is what the error looks like.
2022-04-09 22:08:39.091 ERROR 9672 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'massegeController': Unsatisfied dependency expressed through field 'Massage_repo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'massage_repo' defined in Dyplom.rString.repository.massage_repo defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! Reason: Failed to create query for method public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! No property 'rstringsentsId' found for type 'Masageent'!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! No property 'rstringsentsId' found for type 'Masageent'!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.17.jar:5.3.17]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.17.jar:5.3.17]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.5.jar:2.6.5]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.5.jar:2.6.5]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.5.jar:2.6.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.5.jar:2.6.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.5.jar:2.6.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.5.jar:2.6.5]
at Dyplom.rString.RStringApplication.main(RStringApplication.java:10) ~[main/: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.6.5.jar:2.6.5]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'massage_repo' defined in Dyplom.rString.repository.massage_repo defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! Reason: Failed to create query for method public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! No property 'rstringsentsId' found for type 'Masageent'!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! No property 'rstringsentsId' found for type 'Masageent'!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656) ~[spring-beans-5.3.17.jar:5.3.17]
... 25 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! Reason: Failed to create query for method public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! No property 'rstringsentsId' found for type 'Masageent'!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! No property 'rstringsentsId' found for type 'Masageent'!
at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.6.3.jar:2.6.3]
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) ~[na:na]
at java.base/java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1056) ~[na:na]
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:96) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.6.3.jar:2.6.3]
at java.base/java.util.Optional.map(Optional.java:260) ~[na:na]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:364) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:322) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:328) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.6.3.jar:2.6.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.17.jar:5.3.17]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.17.jar:5.3.17]
... 35 common frames omitted
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List Dyplom.rString.repository.massage_repo.findMassageentByRstringsentsId(java.lang.Long)! No property 'rstringsentsId' found for type 'Masageent'!
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.6.3.jar:2.6.3]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:113) ~[spring-data-jpa-2.6.3.jar:2.6.3]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:254) ~[spring-data-jpa-2.6.3.jar:2.6.3]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:87) ~[spring-data-jpa-2.6.3.jar:2.6.3]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102) ~[spring-data-commons-2.6.3.jar:2.6.3]
... 57 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property 'rstringsentsId' found for type 'Masageent'!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:366) ~[spring-data-commons-2.6.3.jar:2.6.3]
at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:348) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:331) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:249) ~[spring-data-commons-2.6.3.jar:2.6.3]
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:250) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:383) ~[spring-data-commons-2.6.3.jar:2.6.3]
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:384) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:95) ~[spring-data-commons-2.6.3.jar:2.6.3]
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:89) ~[spring-data-jpa-2.6.3.jar:2.6.3]
... 61 common frames omitted
Now i show some code.
RstringEntity.java
package Dyplom.rString.entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "string")
public class RstringsEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name")
private String name;
#Column(name="code")
private String code;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "string_massage",
joinColumns = { #JoinColumn(name = "string_id",referencedColumnName = "id"), },
inverseJoinColumns = { #JoinColumn(name = "massage_id",referencedColumnName = "id") })
private Set<MasageEntity> massagess = new HashSet<>();
public RstringsEntity(String name, String description) {
this.name = name;
this.code = code;
}
public RstringsEntity() {
}
// getters and setters
public void addMassage(MasageEntity massage) {
this.massagess.add(massage);
massage.getMassages().add(this);
}
public void removeMassage(long mId) {
MasageEntity massage = this.massagess.stream().filter(t -> t.getId() == mId).findFirst().orElse(null);
if (massage != null) this.massagess.remove(massage);
massage.getMassages().remove(this);
}
/*
#ManyToMany()
private List<rStringsMassageEntity> massages;
*/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
MassageEntity.java
package Dyplom.rString.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "massages")
public class MasageEntity {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "string_text")
private String string_text;
#Column(name = "string_speed")
private Long string_speed;
#Column(name = "string_color_type")
private Long string_color_type;
#Column(name = "string_color")
private String string_color;
#Column(name = "string_timing_type")
private String string_timing_type;
#Column(name = "string_timing")
private String string_timing;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "massagess")
#JsonIgnore
private Set<RstringsEntity> strings = new HashSet<>();
public MasageEntity() {
}
public long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getString_text() {
return string_text;
}
public void setString_text(String string_text) {
this.string_text = string_text;
}
public Long getString_speed() {
return string_speed;
}
public void setString_speed(Long string_speed) {
this.string_speed = string_speed;
}
public Long getString_color_type() {
return string_color_type;
}
public void setString_color_type(Long string_color_type) {
this.string_color_type = string_color_type;
}
public String getString_color() {
return string_color;
}
public void setString_color(String string_color) {
this.string_color = string_color;
}
public String getString_timing_type() {
return string_timing_type;
}
public void setString_timing_type(String string_timing_type) {
this.string_timing_type = string_timing_type;
}
public String getString_timing() {
return string_timing;
}
public void setString_timing(String string_timing) {
this.string_timing = string_timing;
}
public Set<RstringsEntity> getMassages() {
return strings;
}
public void setTutorials(Set<RstringsEntity> strings) {
this.strings = strings;
}
}
strings_repo.java
package Dyplom.rString.repository;
import Dyplom.rString.entity.RstringsEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface strings_repo extends JpaRepository<RstringsEntity, Long> {
RstringsEntity findByName(String name);
RstringsEntity findRstringsEntitiesById(Long string_id);
List<RstringsEntity> findRstringsEntitiesByMasageEntitiesId(Long massage_id);
}
massage_repo.java
package Dyplom.rString.repository;
import Dyplom.rString.entity.MasageEntity;
import Dyplom.rString.entity.RstringsEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface massage_repo extends JpaRepository <MasageEntity, Long> {
MasageEntity findMasageEntitiesById(Long massage_id);
List<MasageEntity> findMasageEntitiesByRstringsEntitiesId(Long string_id);
List<MasageEntity> findMasageEntityByRstringsEntityId(Long string_id);
}
I don't see the point in showing the controller, since the error occurs elsewhere.
What's I doing wrong? Maybe I need some settings or dependencies? Or I can solve the problem in a different way?
Your problem is the name of the query method: findMasageEntitiesByRstringsEntitiesId(Long. You need to use the field name from your entity class, not the class name.
I would try findMasageEntitiesByStringsId(Long.... (It's also a bit confusing that you've given the variable one name and the getter method another, not sure if JPA will like that.)
The other methods which returns a list also suffer from the same problem.
While creating new user i am getting error as below.
I am using Spring-data-jpa and have created UserRepository for that also.
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
UserDesc.java
#Entity
#Table(name = "USER_DESC")
public class UserDesc implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 758374824732125303L;
private String userId;
private String password;
private String emailId;
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
public UserDesc() {
}
public UserDesc(String userId, String password, String firstName, String updtUserid, Date timeStamp,
String lastAction) {
this.userId = userId;
this.password = password;
this.firstName = firstName;
this.updtUserid = updtUserid;
this.timeStamp = timeStamp;
this.lastAction = lastAction;
}
public UserDesc(String userId, String password, String emailId, Set<UserRole> userRoles) {
this.userId = userId;
this.password = password;
this.emailId = emailId;
this.userRoles = userRoles;
}
public UserDesc(String userId, String emailId, String password) {
this.userId = userId;
this.emailId = emailId;
this.password = password;
}
#Id
#Column(name = "USER_ID", unique = true, nullable = false, length = 50)
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name = "PASSWORD", nullable = false, length = 250)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "EMAIL_ID", length = 100)
public String getEmailId() {
return this.emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER, mappedBy = "userDesc")
public Set<UserRole> getUserRoles() {
return this.userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
UserRole.java
#Entity
#Table(name = "IVMT_USER_ROLE")
public class UserRole implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -7237890967514573717L;
#Id
private UserRoleId id;
private RoleDesc roleDesc;
private UserDesc userDesc;
public UserRole() {
}
public UserRole(UserRoleId id, RoleDesc roleDesc, UserDesc userDesc ) {
this.id = id;
this.roleDesc = roleDesc;
this.userDesc = userDesc;
}
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "userId", column = #Column(name = "USER_ID", nullable = false, length = 50)),
#AttributeOverride(name = "roleName", column = #Column(name = "ROLE_NAME", nullable = false, length = 50)) })
public UserRoleId getId() {
return this.id;
}
public void setId(UserRoleId id) {
this.id = id;
}
#JsonBackReference
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ROLE_NAME", nullable = false, insertable = false, updatable = false)
public RoleDesc getRoleDesc() {
return this.roleDesc;
}
public void setRoleDesc(RoleDesc roleDesc) {
this.roleDesc = roleDesc;
}
#JsonBackReference
#ManyToOne(fetch = FetchType.LAZY)
#JoinTable(name = "IVMT_USER_DESC")
public UserDesc getUserDesc() {
return this.userDesc;
}
public void setUserDesc(UserDesc userDesc) {
this.userDesc = userDesc;
}
}
UserRoleId.java
#Embeddable
public class UserRoleId implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 3699646506024636048L;
private String userId;
private String roleName;
public UserRoleId() {
}
public UserRoleId(String userId, String roleName) {
this.userId = userId;
this.roleName = roleName;
}
#Column(name = "USER_ID", nullable = false, length = 50)
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name = "ROLE_NAME", nullable = false, length = 50)
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
RoleDesc.java
#Entity
#Table(name = "IVMT_ROLE_DESC")
public class RoleDesc implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -3095436060121680832L;
private String roleName;
private String roleDesc;
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
public RoleDesc() {
}
public RoleDesc(String roleName) {
this.roleName = roleName;
}
public RoleDesc(String roleName, String roleDesc,
Set<UserRole> userRoles) {
this.roleName = roleName;
this.roleDesc = roleDesc;
this.userRoles = userRoles;
}
#Id
#Column(name = "ROLE_NAME", unique = true, nullable = false, length = 50)
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#Column(name = "ROLE_DESC")
public String getRoleDesc() {
return this.roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
#JsonBackReference
#OneToMany(fetch = FetchType.LAZY, mappedBy = "roleDesc")
public Set<UserRole> getUserRoles() {
return this.userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
Creating new User code as below.
userDesc = new UserDesc(userId, emailId, password);
Set<UserRole> userRoles = new HashSet<>();
RoleDesc roleDesc = roleRepository.findByRoleName("USER")
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
UserRoleId id = new UserRoleId(signUpRequest.getUserId(), roleDesc.getRoleName());
UserRole userRole = new UserRole(id, roleDesc, userDesc);
userRoles.add(userRole);
userDesc.setUserRoles(userRoles);
userRepository.saveAndFlush(userDesc);
Error Full Stack:
Hibernate: select TOP(?) userdesc0_.user_id as col_0_0_ from ivmt_user_desc userdesc0_ where userdesc0_.user_id=?
Hibernate: select TOP(?) userdesc0_.user_id as col_0_0_ from ivmt_user_desc userdesc0_ where userdesc0_.email_id=?
Hibernate: select roledesc0_.role_name as role_nam1_9_, roledesc0_.last_action as last_act2_9_, roledesc0_.role_desc as role_des3_9_, roledesc0_.time_stamp as time_sta4_9_, roledesc0_.updt_userid as updt_use5_9_ from ivmt_role_desc roledesc0_ where roledesc0_.role_name=?
Hibernate: select userdesc0_.user_id as user_id1_11_0_, userdesc0_.cf_user_date1 as cf_user_2_11_0_, userdesc0_.cf_user_date2 as cf_user_3_11_0_, userdesc0_.cf_user_date3 as cf_user_4_11_0_, userdesc0_.cf_user_date4 as cf_user_5_11_0_, userdesc0_.cf_user_date5 as cf_user_6_11_0_, userdesc0_.cf_user_flag1 as cf_user_7_11_0_, userdesc0_.cf_user_flag2 as cf_user_8_11_0_, userdesc0_.cf_user_flag3 as cf_user_9_11_0_, userdesc0_.cf_user_flag4 as cf_user10_11_0_, userdesc0_.cf_user_flag5 as cf_user11_11_0_, userdesc0_.cf_user_num1 as cf_user12_11_0_, userdesc0_.cf_user_num2 as cf_user13_11_0_, userdesc0_.cf_user_num3 as cf_user14_11_0_, userdesc0_.cf_user_num4 as cf_user15_11_0_, userdesc0_.cf_user_num5 as cf_user16_11_0_, userdesc0_.cf_user_vch1 as cf_user17_11_0_, userdesc0_.cf_user_vch2 as cf_user18_11_0_, userdesc0_.cf_user_vch3 as cf_user19_11_0_, userdesc0_.cf_user_vch4 as cf_user20_11_0_, userdesc0_.cf_user_vch40001 as cf_user21_11_0_, userdesc0_.cf_user_vch40002 as cf_user22_11_0_, userdesc0_.cf_user_vch5 as cf_user23_11_0_, userdesc0_.contact_no as contact24_11_0_, userdesc0_.email_id as email_i25_11_0_, userdesc0_.first_name as first_n26_11_0_, userdesc0_.last_action as last_ac27_11_0_, userdesc0_.last_name as last_na28_11_0_, userdesc0_.middle_name as middle_29_11_0_, userdesc0_.password as passwor30_11_0_, userdesc0_.time_stamp as time_st31_11_0_, userdesc0_.updt_userid as updt_us32_11_0_ from ivmt_user_desc userdesc0_ where userdesc0_.user_id=?
Hibernate: select userrole0_.role_name as role_nam1_12_0_, userrole0_.user_id as user_id2_12_0_, userrole0_.last_action as last_act3_12_0_, userrole0_.role_desc as role_des4_12_0_, userrole0_.time_stamp as time_sta5_12_0_, userrole0_.updt_userid as updt_use6_12_0_, userrole0_.user_desc as user_des7_12_0_ from ivmt_user_role userrole0_ where userrole0_.role_name=? and userrole0_.user_id=?
2020-05-13 15:26:16.857 WARN 8840 --- [onPool-worker-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 207, SQLState: S0001
2020-05-13 15:26:16.857 ERROR 8840 --- [onPool-worker-3] o.h.engine.jdbc.spi.SqlExceptionHelper : Invalid column name 'role_desc'.
2020-05-13 15:26:16.859 INFO 8840 --- [onPool-worker-3] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:390) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:163) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:104) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:197) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4379) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:569) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:537) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:208) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:332) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:108) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:74) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:118) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.fireLoadNoChecks(SessionImpl.java:1168) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1033) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:687) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:464) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.ManyToOneType.resolve(ManyToOneType.java:240) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:457) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.replace(EntityType.java:358) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.CollectionType.replaceElements(CollectionType.java:587) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.CollectionType.replace(CollectionType.java:750) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.AbstractType.replace(AbstractType.java:164) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.TypeHelper.replaceAssociations(TypeHelper.java:254) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:477) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:248) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:318) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:172) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:70) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:775) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:762) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy177.merge(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:557) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.saveAndFlush(SimpleJpaRepository.java:569) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:371) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:204) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:657) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:621) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy179.saveAndFlush(Unknown Source) ~[na:na]
at com.kap.IM.service.impl.UserServiceImpl.createUser(UserServiceImpl.java:99) ~[classes/:na]
at com.kap.IM.controllers.UserController.lambda$4(UserController.java:79) ~[classes/:na]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1582) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[na:1.8.0_92]
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'role_desc'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1624) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:594) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:524) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7194) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2979) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:248) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:223) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:446) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.2.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
... 71 common frames omitted
2020-05-13 15:26:16.865 ERROR 8840 --- [nio-7070-exec-2] c.k.I.a.exception.IvmtExceptionHandler : null
com.kap.IM.api.exception.IvmtException: Unable to create new user
at com.kap.IM.api.IvmtBaseRestController.buildErrorResponse(IvmtBaseRestController.java:27) ~[classes/:na]
at com.kap.IM.controllers.UserController.lambda$5(UserController.java:87) ~[classes/:na]
at java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:760) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:736) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1595) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1582) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[na:1.8.0_92]
Caused by: java.util.concurrent.CompletionException: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:273) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:280) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1592) ~[na:1.8.0_92]
... 5 common frames omitted
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy179.saveAndFlush(Unknown Source) ~[na:na]
at com.kap.IM.service.impl.UserServiceImpl.createUser(UserServiceImpl.java:99) ~[classes/:na]
at com.kap.IM.controllers.UserController.lambda$4(UserController.java:79) ~[classes/:na]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) ~[na:1.8.0_92]
... 5 common frames omitted
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:390)
2020-05-13 15:26:16.868 WARN 8840 --- [nio-7070-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [com.kap.IM.api.exception.IvmtException: Unable to create new user]
Let me know where I am making mistake in setting proper joins between tables.
Ive created a simple 3 entities data model and when trying to persist data its not working.
Here are the entities and their id classes, server:
#Entity
#Data
public class Server {
#Id
private String name;
private String serverUrl;
#OneToMany(mappedBy = "server", fetch = FetchType.LAZY)
private List<Service> services;
}
Service:
#Entity
#IdClass(ServiceId.class)
public class Service {
#Id
private String name;
#Id
#ManyToOne(fetch = FetchType.LAZY)
private Server server;
#OneToMany(mappedBy = "service", fetch = FetchType.EAGER)
private List<Container> containers;
}
public class ServiceId implements Serializable {
private String name;
private Server server;
}
Container:
#Entity
#IdClass(ContainerId.class)
public class Container {
#Id
private String name;
#Id
#ManyToOne(fetch = FetchType.LAZY)
private Service service;
private String command;
private String state;
private String ports;
}
#Data
public class ContainerId implements Serializable {
private String name;
private Service service;
}
What im trying to do is using ServiceRepository:
public interface ServiceRepository extends JpaRepository<Service, ServiceId> {
}
to persist a service object:
public class SomeClass{
#Autowired
ServiceRepository serviceRepository;
#Transactional
public void insertServices(Service service) {
serviceRepository.save(service); <- Exception HERE!
}
}
The service object contain a Server which is already in the DB at server table, the service itself which is not in the db yet and a list of containers which are not in the db yet(and should also be persistant now).
The error im getting when doing that is:
org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'a.servers.Server' for property 'server'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'a.servers.Server' for property 'server': no matching editors or conversion strategy found
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:590) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:604) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:453) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:246) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.data.util.DirectFieldAccessFallbackBeanWrapper.setPropertyValue(DirectFieldAccessFallbackBeanWrapper.java:75) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation$IdentifierDerivingDirectFieldAccessFallbackBeanWrapper.setPropertyValue(JpaMetamodelEntityInformation.java:358) ~[spring-data-jpa-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.getId(JpaMetamodelEntityInformation.java:166) ~[spring-data-jpa-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.repository.core.support.AbstractEntityInformation.isNew(AbstractEntityInformation.java:42) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.isNew(JpaMetamodelEntityInformation.java:237) ~[spring-data-jpa-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:553) ~[spring-data-jpa-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_172]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_172]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_172]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_172]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:371) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:204) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:657) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:621) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:353) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at com.sun.proxy.$Proxy96.save(Unknown Source) ~[na:na]
at a.services.ServiceService.updateServices(ServiceService.java:20) ~[classes/:na]
at a.services.ServiceService$$FastClassBySpringCGLIB$$7cf24811.invoke() ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:353) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at a.services.ServiceService$$EnhancerBySpringCGLIB$$a987bcb2.updateServices() ~[classes/:na]
at a.agents.DataFetcher.fetch(DataFetcher.java:48) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_172]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_172]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_172]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_172]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) [spring-context-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_172]
at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266) [na:1.8.0_172]
at java.util.concurrent.FutureTask.run(FutureTask.java) [na:1.8.0_172]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_172]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_172]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_172]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_172]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_172]
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'a.servers.Server' for property 'server': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:262) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
... 62 common frames omitted
i have spring -> jpa -> show-sql set to true in application.yml so i do get this log before it fails:
Hibernate: select server0_.name as name1_1_, server0_.server_url as server_u2_1_ from server server0_
Created DB seems ok:
I also had problems with a similar composite key in my current project.
Maybe I'm wrong, but for me it seems that #IdClass only works if none of the #Id annotated properties are foreign keys.
I finally refactored my entities by using #EmbeddedId instead.
...
Actually I have one more idea: try adding the #ManyToOne annotation to server property in the ServiceId class too:
public class ServiceId implements Serializable {
private String name;
#OneToMany(mappedBy = "service", fetch = FetchType.EAGER)
private Server server;
}
How to select referenced entities in One-To-May relationship with Spring Data JDBC?
When I tried following code on this blog
class PurchaseOrder {
#Id
private Long id;
private String shippingAddress;
private Set<OrderItem> items;
}
class OrderItem {
#Id
private Long id;
private int quantity;
private String product;
}
#Test
void test() {
PurchaseOrder purchaseOrder = PurchaseOrder.of("Tokyo");
purchaseOrder.addItem(4, "Captain Future Comet Lego set");
purchaseOrder.addItem(2, "Cute blue angler fish plush toy");
orderRepository.save(purchaseOrder);
Iterable<PurchaseOrder> result = orderRepository.findAll(); //throw MappingException !!
result.forEach(System.out::println);
}
this throws an exception below:
org.springframework.data.mapping.MappingException: Could not read property #org.springframework.data.annotation.Id()private final java.lang.Long com.example.demo.OrderItem.id from result set!
at org.springframework.data.jdbc.core.EntityRowMapper.readFrom(EntityRowMapper.java:130)
at org.springframework.data.jdbc.core.EntityRowMapper.readEntityFrom(EntityRowMapper.java:143)
at org.springframework.data.jdbc.core.EntityRowMapper.readFrom(EntityRowMapper.java:124)
at org.springframework.data.jdbc.core.EntityRowMapper.lambda$createInstance$0(EntityRowMapper.java:167)
......
Caused by: org.h2.jdbc.JdbcSQLException: Column "items_id" not found [42122-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
......
It looks that spring data jdbc add the parent entity's name as prefix to columns of child entities when retrieving values from ResultSet. But I couldn't this mapping rule on the document...
Is there any way to custom this mapping rule?
DDL:
create table purchase_order (
id bigint primary key auto_increment,
shipping_address varchar NOT NULL
);
create table order_item (
id bigint primary key auto_increment,
purchase_order bigint NOT NULL,
quantity int NOT NULL,
product varchar NOT NULL
);
[UPDATED]
The version of spring-data-jdbc is 1.0.4.RELEASE.
The SQL statements is here:
2019-01-29 23:49:16.932 DEBUG 80409 --- [ main] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL statement [SELECT purchase_order.id AS id, purchase_order.shipping_address AS shipping_address FROM purchase_order]
And full stack trace is
org.springframework.data.mapping.MappingException: Could not read property #org.springframework.data.annotation.Id()private java.lang.Long com.example.demo.OrderItem.id from result set!
at org.springframework.data.jdbc.core.EntityRowMapper.readFrom(EntityRowMapper.java:130)
at org.springframework.data.jdbc.core.EntityRowMapper.readEntityFrom(EntityRowMapper.java:143)
at org.springframework.data.jdbc.core.EntityRowMapper.readFrom(EntityRowMapper.java:124)
at org.springframework.data.jdbc.core.EntityRowMapper.lambda$createInstance$0(EntityRowMapper.java:167)
at org.springframework.data.relational.core.conversion.BasicRelationalConverter$ConvertingParameterValueProvider.getParameterValue(BasicRelationalConverter.java:251)
at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:75)
at org.springframework.data.convert.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:84)
at org.springframework.data.relational.core.conversion.BasicRelationalConverter.createInstance(BasicRelationalConverter.java:141)
at org.springframework.data.jdbc.core.EntityRowMapper.createInstance(EntityRowMapper.java:160)
at org.springframework.data.jdbc.core.EntityRowMapper.mapRow(EntityRowMapper.java:71)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:94)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:61)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:679)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:617)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:669)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:694)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:748)
at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:215)
at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:227)
at org.springframework.data.jdbc.core.DefaultDataAccessStrategy.findAll(DefaultDataAccessStrategy.java:217)
at org.springframework.data.jdbc.core.JdbcAggregateTemplate.findAll(JdbcAggregateTemplate.java:158)
at org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.findAll(SimpleJdbcRepository.java:84)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy68.findAll(Unknown Source)
at com.example.demo.OrderRepositoryTest.test(OrderRepositoryTest.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:532)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:108)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.h2.jdbc.JdbcSQLException: Column "items_id" not found [42122-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.jdbc.JdbcResultSet.getColumnIndex(JdbcResultSet.java:3174)
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3247)
at org.h2.jdbc.JdbcResultSet.getObject(JdbcResultSet.java:529)
at org.springframework.data.jdbc.core.EntityRowMapper.readFrom(EntityRowMapper.java:127)
... 86 more
Following copied from official docs.
To wrap it up: Spring Data JDBC does not support many-to-one or many-to-many relationships. In order to model these, use IDs. This encourages a clean modularization of the domain model. It also removes a whole type of questions that one would have to solve and learn to reason about if such a mapping were possible.
class PurchaseOrder {
#Id
private Long id;
private String shippingAddress;
private Set<OrderItem> items;
private OrderItemRef createOrderItem(OrderItem orderItem ) {
OrderItemRef orderItemRef = new OrderItemRef ();
orderItemRef.orderItem = orderItemRef.id;
return orderItemRef ;
}
}
#Table("Purchase_OrderItem ")
class OrderItemRef {
Long orderItem;
}
class OrderItem {
#Id
private Long id;
private int quantity;
private String product;
}
Is the Predicate supposed to be nullable using MongoRepository?
The standard JPA PagingAndSortingRepository always seems to return a valid Predicate, no matter which query parameters are provided.
Stacktrace
java.lang.IllegalArgumentException: Predicate must not be null!
at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.data.mongodb.repository.support.QuerydslMongoPredicateExecutor.findAll(QuerydslMongoPredicateExecutor.java:165) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
Curl
http://localhost:8080/api/notifications?page=1 # stacktrace
http://localhost:8080/api/notifications?id=1&page=1" # does work
Controller
#RestController
#RequestMapping(produces = "application/json; charset=UTF-8")
#Api(description = "Operations concerning notifications")
public class NotificationController {
#Autowired
private NotificationFacade notificationFacade;
#Autowired
private NotificationRepository notificationRepository;
#ApiOperation(value = "Retrieve a list of available notifications")
#GetMapping("/api/notifications")
public Page<Notification> findAll(#QuerydslPredicate() Predicate predicate,
#PageableDefault(sort = "id") Pageable pageable) {
return notificationRepository.findAll(predicate, pageable);
}
}
Repository
public interface NotificationRepository extends MongoRepository<Notification, String>, QuerydslPredicateExecutor<Notification> {}
Entity
#Data
#Document(collection = "notifications")
public class Notification {
#Id
private String id;
#NonNull
private String message;
}
Add an extra check
if (predicate == null) {
predicate = QNotification.notification.id.ne("");
}
return notificationRepository.findAll(predicate, pageable);
my problem was sorted out by a new compiler plugin block in pom.xml with lombok-mapstruct-binding, not to generate mapstruct before lombok getters setters have been done - special thx for my teacher # BME for the solution : ]