Validation failed for query for method public abstract long com.rajesh.repository.CreditDebitRepository.fingById(long) - postgresql

I have a 3 table Credit is parent table Debit is child table and credit_debit is reference table given relation one to many. i want to get record based on cid
I have write query for getting that record from that two table but some error is display in console regarding hibernate Query. any one can help me how to write query for get record by id from two table in third table all two table id is stored.
1.Credit.java
package com.rajesh.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debits) {
this.debits = debits;
}
#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}
}
2.Debit.java
package com.rajesh.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
3.CreditDebitRepository.java
#Repository
public interface CreditDebitRepository extends JpaRepository<Credit, Long>{
#Query(value= "from Credit c join credit_debit cd on(c.cid=cd.c_id) join Debit d on(cd.d_id=d.did) WHERE c.cid=:cid")
long fingById(long cid);
}
4.CreditDebitService.java
package com.rajesh.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rajesh.model.Credit;
import com.rajesh.repository.CreditDebitRepository;
#Service
public class CreditDebitService {
#Autowired
CreditDebitRepository creditDebitRepository;
public void save(Credit credit) {
creditDebitRepository.save(credit);
}
public List<Credit> getAllCreditList() {
return creditDebitRepository.findAll();
}
public long getCreditDebitById(long cid) {
cid = creditDebitRepository.fingById(cid);
return cid;
}
5.CreditDebitController.java
package com.rajesh.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rajesh.model.Credit;
import com.rajesh.model.Debit;
import com.rajesh.model.User;
import com.rajesh.service.CreditDebitService;
#Controller
public class CreditDebitController {
#Autowired
CreditDebitService creditDebitService;
#PostMapping("/user/savecreditdebit")
public String saveCreditDebit(#RequestParam(value = "amount") String[] amount,
#RequestParam(value = "description") String[] description,
ModelMap model, HttpServletRequest request, HttpSession session,#ModelAttribute("command")Credit credit, BindingResult result) {
try {
List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
debits = credit.getDebit();
for(int i=0; i<amount.length; i++) {
Debit debit = new Debit();
debit.setAmount(amount[i]);
debit.setDescription(description[i]);
debits.add(debit);
}
System.out.println("debits ="+debits);
List<Debit> debits1 = new ArrayList<Debit>();
for(int i=0; i<debits.size(); i++)
{
debits1.add(new Debit(debits.get(i).getAmount(),debits.get(i).getDescription()));
}
System.out.println("debits1 ="+debits1);
User user = new User();
// Credit Data Set
credit.setOpeningbalance(credit.getOpeningbalance());
credit.setDate(credit.getDate());
System.out.println("Date is: = "+credit.getDate());
credit.setDebittotal(credit.getDebittotal());
credit.setDrawertotal(credit.getDrawertotal());
credit.setDebittotalplusdrawertotal(credit.getDebittotalplusdrawertotal());
credit.setTodaybusiness(credit.getTodaybusiness());
credit.setCreatedBy(user.getEmail());
credit.setCreatedDate(new Date());
credit.setUpdatedBy(user.getEmail());
credit.setUpdatedDate(new Date());
// Debit Data set
System.out.println("Debit List = " + debits1.size());
System.out.println("Credit and Debit data seved successfully");
credit.setDebit(debits1);
creditDebitService.save(credit);
model.put("success", "Data Saved Successfully");
}catch(Exception e) {
e.printStackTrace();
}
return "redirect:userdashboard";
}
#GetMapping("/user/getCreditDebit/{cid}")
#ResponseBody
public String getCreditDebitById(#PathVariable("cid") long cid, #ModelAttribute("command") Credit credit, HttpSession session, HttpServletRequest request, BindingResult result) {
creditDebitService.getCreditDebitById(cid);
return "redirect:userdashboard";
}
}
6.Error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'creditDebitController': Unsatisfied dependency expressed through field 'creditDebitService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'creditDebitService': Unsatisfied dependency expressed through field 'creditDebitRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditDebitRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract long com.rajesh.repository.CreditDebitRepository.fingById(long)!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at com.rajesh.RojmatBootApplication.main(RojmatBootApplication.java:16) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.4.RELEASE.jar:2.0.4.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'creditDebitService': Unsatisfied dependency expressed through field 'creditDebitRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditDebitRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract long com.rajesh.repository.CreditDebitRepository.fingById(long)!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditDebitRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract long com.rajesh.repository.CreditDebitRepository.fingById(long)!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
... 37 common frames omitted
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract long com.rajesh.repository.CreditDebitRepository.fingById(long)!
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:63) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:139) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:553) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:546) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_191]
at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_191]
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049) ~[na:1.8.0_191]
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:1.8.0_191]
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_191]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_191]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_191]
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_191]
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_191]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:548) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:538) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at java.util.Optional.map(Optional.java:215) ~[na:1.8.0_191]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:538) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:317) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:286) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:63) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:289) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
... 47 common frames omitted
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [from com.rajesh.model.Credit c join credit_debit cd on(c.cid=cd.c_id) join com.rajesh.model.Debit d on(cd.d_id=d.did) WHERE c.cid=:cid]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350) ~[spring-orm-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at com.sun.proxy.$Proxy103.createQuery(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87) ~[spring-data-jpa-2.0.9.RELEASE.jar:2.0.9.RELEASE]
... 76 common frames omitted
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [from com.rajesh.model.Credit c join credit_debit cd on(c.cid=cd.c_id) join com.rajesh.model.Debit d on(cd.d_id=d.did) WHERE c.cid=:cid]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:91) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:272) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
... 84 common frames omitted

This problem is solved by me. I will used findById(cid); they will return particular id related data from thiese two table I has used JPA repository

Related

(SpringBoot, JPA, Mysql) Error configuring logic to store user

Used : Mysql, JPA, SpringBoot
The following is the information I requested in Json format.
{
"id" : "abc#naver.com",
"password" : "abc1234",
"name" : "hi",
"phoneNumber" : "01012341234",
"ssn" : "0000000000000",
"cityName" : "seoul",
"townName" : "shinjeongdong",
"streetName" : "teheranro-22",
"zipCode" : "55950",
"dateils" : "5 floor"
}
Failed to configure logic to receive values through 'UserInfoDto' using PostMapping and store values in the 'Users' table.
I don't know what's wrong...
'Users' Entity
package My_Project.integration.entity;
import My_Project.integration.entity.Dto.UserInfoDto;
import lombok.*;
import javax.persistence.*;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
#Entity
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Setter
#Table(uniqueConstraints = {#UniqueConstraint(columnNames = {"ssn","phone_number"})})
public class Users {
#Column(name = "id", length = 40, updatable = false, nullable = false)
#Id
private String id;
#Column(name = "password", length = 20, nullable = false)
private String password;
#Column(name = "name", length = 25, nullable = false)
private String name;
#Column(name = "phone_number", length = 12, nullable = false)
private String phoneNumber;
#Column(name = "ssn", length = 13, nullable = false, updatable = false)
private String ssn;
#Embedded
private Address address;
#Column(name = "point")
private Long point;
#OneToMany(mappedBy = "postedUser")
private List<PostInfo> uploadedPost = new ArrayList<>();
#OneToMany(mappedBy = "userId")
private List<PointHistory> pointHistories = new ArrayList<>();
#Embedded
private Dates dates;
public Users(UserInfoDto userInfoDto){
this.setId(userInfoDto.getId());
this.setPassword(userInfoDto.getPassword());
this.setPhoneNumber(userInfoDto.getPhoneNumber());
this.setSsn(userInfoDto.getSsn());
this.setPoint(0L);
Address address = new Address(
userInfoDto.getCityName(),
userInfoDto.getTownName(),
userInfoDto.getStreetName(),
userInfoDto.getZipCode(),
userInfoDto.getDetailsCode()
);
this.setAddress(address);
List<PostInfo> postInfoList = new ArrayList<>();
List<PointHistory> pointHistoryList = new ArrayList<>();
this.setUploadedPost(postInfoList);
this.setPointHistories(pointHistoryList);
Dates dates = new Dates(LocalDateTime.now(), LocalDateTime.now());
this.setDates(dates);
}
}
It's Entity 'Address', an embedded entity in 'Users'.
package My_Project.integration.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
#Getter
#AllArgsConstructor
public class Address {
#Column(name = "city_name", nullable = false) //도시명
private String cityName;
#Column(name = "town_name", length = 20) //동명
private String townName;
#Column(name = "street_name", length = 20, nullable = false) //도로명
private String streetName;
#Column(name = "zip_code", length = 20) // 우편번호
private String zipCode;
#Column(name = "details",length = 20) //상세주소
private String detailsCode;
protected Address() {
}
}
This is the Dto to use instead of the 'Users' entity.
package My_Project.integration.entity.Dto;
import My_Project.integration.entity.PointHistory;
import My_Project.integration.entity.PostInfo;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
#Setter
#Getter
public class UserInfoDto {
private String id;
private String password;
private String name;
private String phoneNumber;
private String ssn;
private String cityName;
private String townName;
private String streetName;
private String zipCode;
private String detailsCode;
private Long point;
public UserInfoDto(String id, String password, String name, String phoneNumber, String ssn, String cityName, String townName, String streetName, String zipCode, String detailsCode, Long point) {
this.id = id;
this.password = password;
this.name = name;
this.phoneNumber = phoneNumber;
this.ssn = ssn;
this.cityName = cityName;
this.townName = townName;
this.streetName = streetName;
this.zipCode = zipCode;
this.detailsCode = detailsCode;
this.point = point;
}
public UserInfoDto() {
}
}
package My_Project.integration.controller;
import My_Project.integration.entity.*;
import My_Project.integration.entity.Dto.UserInfoDto;
import My_Project.integration.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
#Controller
#RequiredArgsConstructor
public class SignupPageController {
#Autowired private UserService userService;
#PostMapping("/signup_execute")
public String signUp(UserInfoDto userInfoDto) {
try {
Users users = new Users(userInfoDto);
userService.addUsers(users);
} catch (Exception e){
e.printStackTrace();
return "redirect:/errorpage";
}
return "redirect:/";
}
}
package My_Project.integration.service;
import My_Project.integration.entity.Users;
import My_Project.integration.repository.UsersRepository;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
#Service
#RequiredArgsConstructor
#Getter
public class UserService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Users addUsers(Users users) throws Exception{
if (!usersRepository.duplicateCheck(users)) {
throw new Exception("중복된 값이 검출되었습니다.");
} else {
usersRepository.save(users);
System.out.println("Users 엔티티를 저장하였습니다.");
return users;
}
}
}
package My_Project.integration.repository.UserCustom.Impl;
import My_Project.integration.entity.Users;
import My_Project.integration.repository.UserCustom.UserCustomRepository;
import lombok.RequiredArgsConstructor;
import net.bytebuddy.implementation.bytecode.Throw;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.text.html.Option;
import java.util.List;
import java.util.Optional;
#RequiredArgsConstructor
public class UserCustomRepositoryImpl implements UserCustomRepository {
private final EntityManager em;
#Override
public boolean duplicateCheck(Users users) {
Query query1 = em.createQuery("select u from Users u where u.id = :name",Users.class)
.setParameter("name",users.getId());
List resultList1 = query1.getResultList();
if(!resultList1.isEmpty()) return false;
Query query2 = em.createQuery("select u from Users u where u.phoneNumber= :name",Users.class)
.setParameter("name",users.getPhoneNumber());
List resultList2 = query2.getResultList();
if(!resultList2.isEmpty()) return false;
Query query3 = em.createQuery("select u from Users u where u.ssn = :name",Users.class)
.setParameter("name",users.getSsn());
List resultList3 = query3.getResultList();
if(!resultList3.isEmpty()) return false;
return true;
}
}
It's error content....
org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save(): My_Project.integration.entity.Users; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): My_Project.integration.entity.Users
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at jdk.proxy4/jdk.proxy4.$Proxy109.save(Unknown Source)
at My_Project.integration.service.UserService.addUsers(UserService.java:26)
at My_Project.integration.service.UserService$$FastClassBySpringCGLIB$$636d190f.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
at My_Project.integration.service.UserService$$EnhancerBySpringCGLIB$$7615f959.addUsers(<generated>)
at My_Project.integration.controller.SignupPageController.signUp(SignupPageController.java:24)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:696)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): My_Project.integration.entity.Users
at org.hibernate.id.Assigned.generate(Assigned.java:33)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:115)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:742)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
at jdk.proxy4/jdk.proxy4.$Proxy105.persist(Unknown Source)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
at jdk.proxy4/jdk.proxy4.$Proxy105.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:666)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:81)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
... 71 more
Successful data storage was expected, but it was not.

javax.persistence.RollbackException: Error while committing the transaction in Eclipse

I'm trying to create an application in JPA using Eclipse . the UML model of the application is the following :
enter image description here
And I have the error in class called "GRADETEST.java" in the function shouldSaveGrade() .
In this function I create variable grade final var grade = Fixtures.createGrade(subject).
before doing this I initialize a variable called subject which is fictitious . So when I do Junit test it crashes at the line
"entityManager.getTransaction().commit();"
I send to you Grade , subject , GRADETEST ,SubjectTest classes .
I'm new in this domain so I don't know why does this error appears .
javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:81)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
at fr.uga.im2ag.l3.miage.db.repository.GradeTest.shouldSaveGrade(GradeTest.java:51)
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:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:65)
... 71 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:37)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3375)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3908)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:344)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1402)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3285)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2420)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:449)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
... 70 more
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Intégrité référentielle violation de contrainte: "FKEP37YMUXQE45LFAYSRIMBRS2A: PUBLIC.GRADE FOREIGN KEY(SUBJECT_ID) REFERENCES PUBLIC.SUBJECT(ID) (CAST(1 AS BIGINT))"
Referential integrity constraint violation: "FKEP37YMUXQE45LFAYSRIMBRS2A: PUBLIC.GRADE FOREIGN KEY(SUBJECT_ID) REFERENCES PUBLIC.SUBJECT(ID) (CAST(1 AS BIGINT))"; SQL statement:
insert into Grade (subject_id, gradevalue, weight, id) values (?, ?, ?, ?) [23506-210]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:527)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.constraint.ConstraintReferential.checkRowOwnTable(ConstraintReferential.java:311)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:252)
at org.h2.table.Table.fireConstraints(Table.java:1177)
at org.h2.table.Table.fireAfterRow(Table.java:1195)
at org.h2.command.dml.Insert.insertRows(Insert.java:188)
at org.h2.command.dml.Insert.update(Insert.java:135)
at org.h2.command.dml.DataChangeStatement.update(DataChangeStatement.java:61)
at org.h2.command.CommandContainer.update(CommandContainer.java:174)
at org.h2.command.Command.executeUpdate(Command.java:252)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:209)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:169)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 90 more
//GradeTEST
package fr.uga.im2ag.l3.miage.db.repository;
import java.sql.Date;
import java.time.LocalDate;
import fr.uga.im2ag.l3.miage.db.repository.api.GradeRepository;
import fr.uga.im2ag.l3.miage.db.repository.api.SubjectRepository;
import fr.uga.im2ag.l3.miage.db.model.*;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class GradeTest extends Base {
GradeRepository gradeRepository;
#BeforeEach
void before() {
gradeRepository = daoFactory.newGradeRepository(entityManager);
}
#AfterEach
void after() {
if (entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
}
}
#Test
void shouldSaveGrade() {
// TODO
final var subject = Fixtures.createSubject();
subject.setId((long)1);
subject.setName("Math");
subject.setHours((float) 5.0);
// Create a date object
Date d = new Date(2022,2,28);
subject.setStart(d);
subject.setPoints(5);
subject.setEnd(d);
final var grade = Fixtures.createGrade(subject) ;
entityManager.getTransaction().begin();
gradeRepository.save(grade);
entityManager.getTransaction().commit();
entityManager.detach(grade);
var pGrade = gradeRepository.findById(grade.getId());
assertThat(pGrade).isNotNull().isNotSameAs(grade);
assertThat(pGrade.getValue()).isEqualTo(grade.getValue());
assertThat(pGrade.getWeight()).isEqualTo(grade.getWeight());
}
//Grade
package fr.uga.im2ag.l3.miage.db.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
//#Table(name="Grade")
// TODO ajouter une named query pour une des requêtes à faire dans le repository
public class Grade {
#Id
#GeneratedValue()
#Column(name = "id")
private Long id;
#ManyToOne
private Subject subject;
#Column(name = "gradevalue")
private Float value;
private Float weight;
public Long getId() {
return id;
}
public Subject getSubject() {
return subject;
}
public Grade setSubject(Subject subject) {
this.subject = subject;
return this;
}
public Float getValue() {
return value;
}
public Grade setValue(Float value) {
this.value = value;
return this;
}
public Float getWeight() {
return weight;
}
public Grade setWeight(Float weight) {
this.weight = weight;
return this;
}
}
//Subject
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Entity
#Table(name = "Subject")
// TODO ajouter une named query pour une des requêtes à faire dans le repository
public class Subject {
#Id
#GeneratedValue()
#Column(name = "id",nullable=false)
private Long id;
private String name;
private Integer points;
private Float hours;
private Date start;
#Column(name = "end_date")
private Date end;
public Long getId() {
return id;
}
public Subject setId(Long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Subject setName(String name) {
this.name = name;
return this;
}
public Integer getPoints() {
return points;
}
public Subject setPoints(Integer points) {
this.points = points;
return this;
}
public Float getHours() {
return hours;
}
public Subject setHours(Float hours) {
this.hours = hours;
return this;
}
public Date getStart() {
return start;
}
public Subject setStart(Date start) {
this.start = start;
return this;
}
public Date getEnd() {
return end;
}
public Subject setEnd(Date end) {
this.end = end;
return this;
}
}
Referential integrity constraint violation: "FKEP37YMUXQE45LFAYSRIMBRS2A: PUBLIC.GRADE FOREIGN KEY(SUBJECT_ID) REFERENCES PUBLIC.SUBJECT(ID) (CAST(1 AS BIGINT))"; SQL statement: insert into Grade (subject_id, gradevalue, weight, id) values (?, ?, ?, ?)
Here Grade is dependent on Subject
and you're trying to save Grade without saving Subject
It'll work if you just save Subject
as Subject and Grade have a relation; it'll save Grade as well

java.lang.IllegalArgumentException: The attribute [state_id] is not present in the managed type [EntityTypeImpl#530144602:Cities]

I'm new in javaEE. recently I'm working on restful Web Services using jax-rs and using JPA for working with databases and using Netbeans as an IDE and TomeEE as Web Server.
about my problem,
I have a table that was called cities which have 3 column :
id, state_id, name
(state_id is defined as foreign key to another column is called states)
I want to select all cities which have a certain state_id, for example in the table, 1000 rows exist that their state_id are 8.
this is my JPA code:
public List<T> findByStateID(Short id){
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(entityClass);
javax.persistence.criteria.Root<T> r = cq.from(entityClass);
cq.select(r);
cq.where(getEntityManager().getCriteriaBuilder().equal(r.get("state_id"), id));
return getEntityManager().createQuery(cq).getResultList();
}
and this is the Web Service code:
#GET
#Path("State/{id}")
#Produces(MediaType.APPLICATION_JSON)
public List<Cities> findByState(#PathParam("id") Short id){
return super.findByStateID(id);
}
know my problem is that when I access to the target url I get blow error:
HTTP Status 500 - Error processing webservice request
type Exception report
message Error processing webservice request
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error processing webservice request
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
java.lang.IllegalArgumentException: The attribute [state_id] is not present in the managed type [EntityTypeImpl#530144602:Cities [ javaType: class entity.Cities descriptor: RelationalDescriptor(entity.Cities --> [DatabaseTable(cities)]), mappings: 4]].
org.eclipse.persistence.internal.jpa.metamodel.ManagedTypeImpl.getAttribute(ManagedTypeImpl.java:148)
org.eclipse.persistence.internal.jpa.querydef.FromImpl.get(FromImpl.java:312)
rest.AbstractFacade.findByStateID(AbstractFacade.java:50)
rest.CitiesFacadeREST.findByState(CitiesFacadeREST.java:49)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:236)
org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:203)
org.apache.openejb.util.proxy.ProxyEJB$Handler.invoke(ProxyEJB.java:74)
rest.CitiesFacadeREST$$LocalBeanProxy.findByState(rest/CitiesFacadeREST.java)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.performInvocation(OpenEJBEJBInvoker.java:95)
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:189)
org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.invoke(OpenEJBEJBInvoker.java:68)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:99)
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:64)
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:254)
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:251)
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat (TomEE)/8.5.3 (7.0.1) logs.
Apache Tomcat (TomEE)/8.5.3 (7.0.1)
here is the Cities entity class:
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author seyed
*/
#Entity
#Table(name = "cities")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Cities.findAll", query = "SELECT c FROM Cities c"),
#NamedQuery(name = "Cities.findById", query = "SELECT c FROM Cities c WHERE c.id = :id"),
#NamedQuery(name = "Cities.findByName", query = "SELECT c FROM Cities c WHERE c.name = :name")})
public class Cities implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Short id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 65)
#Column(name = "name")
private String name;
#JoinColumn(name = "state_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private States stateId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "city")
private Collection<Users> usersCollection;
public Cities() {
}
public Cities(Short id) {
this.id = id;
}
public Cities(Short id, String name) {
this.id = id;
this.name = name;
}
public Short getId() {
return id;
}
public void setId(Short id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public States getStateId() {
return stateId;
}
public void setStateId(States stateId) {
this.stateId = stateId;
}
#XmlTransient
public Collection<Users> getUsersCollection() {
return usersCollection;
}
public void setUsersCollection(Collection<Users> usersCollection) {
this.usersCollection = usersCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cities)) {
return false;
}
Cities other = (Cities) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Cities[ id=" + id + " ]";
}
}
as said in comments , I changed state_id to stateId in jpa part and now I get this error:
HTTP Status 500 - Error processing webservice request
type Exception report
message Error processing webservice request
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error processing webservice request
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
javax.persistence.PersistenceException: Exception [EclipseLink-6078] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.QueryException
Exception Description: The class of the argument for the object comparison is incorrect.
Expression: [
Base entity.Cities]
Mapping: [org.eclipse.persistence.mappings.ManyToOneMapping[stateId]]
Argument: [1]
Query: ReadAllQuery(referenceClass=Cities )
org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:484)
rest.AbstractFacade.findByStateID(AbstractFacade.java:51)
rest.CitiesFacadeREST.findByState(CitiesFacadeREST.java:49)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:236)
org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:203)
org.apache.openejb.util.proxy.ProxyEJB$Handler.invoke(ProxyEJB.java:74)
rest.CitiesFacadeREST$$LocalBeanProxy.findByState(rest/CitiesFacadeREST.java)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.performInvocation(OpenEJBEJBInvoker.java:95)
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:189)
org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.invoke(OpenEJBEJBInvoker.java:68)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:99)
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:64)
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:254)
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:251)
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
Exception [EclipseLink-6078] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.QueryException
Exception Description: The class of the argument for the object comparison is incorrect.
Expression: [
Base entity.Cities]
Mapping: [org.eclipse.persistence.mappings.ManyToOneMapping[stateId]]
Argument: [1]
Query: ReadAllQuery(referenceClass=Cities )
org.eclipse.persistence.exceptions.QueryException.incorrectClassForObjectComparison(QueryException.java:601)
org.eclipse.persistence.mappings.OneToOneMapping.buildObjectJoinExpression(OneToOneMapping.java:298)
org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:830)
org.eclipse.persistence.internal.expressions.SQLSelectStatement.normalize(SQLSelectStatement.java:1474)
org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.buildNormalSelectStatement(ExpressionQueryMechanism.java:550)
org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.prepareSelectAllRows(ExpressionQueryMechanism.java:1722)
org.eclipse.persistence.queries.ReadAllQuery.prepareSelectAllRows(ReadAllQuery.java:885)
org.eclipse.persistence.queries.ReadAllQuery.prepare(ReadAllQuery.java:816)
org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:666)
org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:911)
org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:615)
org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:872)
org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1134)
org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:460)
org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1222)
org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1857)
org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1839)
org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:473)
rest.AbstractFacade.findByStateID(AbstractFacade.java:51)
rest.CitiesFacadeREST.findByState(CitiesFacadeREST.java:49)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:236)
org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:203)
org.apache.openejb.util.proxy.ProxyEJB$Handler.invoke(ProxyEJB.java:74)
rest.CitiesFacadeREST$$LocalBeanProxy.findByState(rest/CitiesFacadeREST.java)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.performInvocation(OpenEJBEJBInvoker.java:95)
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:189)
org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.invoke(OpenEJBEJBInvoker.java:68)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:99)
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:64)
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:254)
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:251)
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat (TomEE)/8.5.3 (7.0.1) logs.
Apache Tomcat (TomEE)/8.5.3 (7.0.1)
The querying uses by default java names. If you have doubt you can setup a jpa metamodel generator and you will be able to use a typed version of the attributes instead of strings.
because jpa/hibernate use propertynames and not column names you have to use private States stateId instead of private States state_Id.
So you have to Change equal(r.get("state_id"), id)) to equal(r.get("stateId"), id));
`

Spring Data JPA with QueryDSL issue with JPA Inheritance.JOINED strategy when subclasses have the same property name

I am trying to use QueryDSL for a dynamic query that I need to do. This is a Spring Boot project with QueryDSL 3.7.2 (com.mysema.querydsl). I have simplified the example, but basically I have an Item abstract class annotated with with an Inheritance.JOINED strategy. This is the Item class:
package org.porthos.concepts.domain;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
#Entity
#Table(name = "item")
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name = "item_type")
public abstract class Item {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "item_type", insertable = false, updatable = false)
private ItemType type;
#Column(name = "title")
private String title;
protected Item() {}
public Long getId() {
return id;
}
public ItemType getType() {
return type;
}
public String getTitle() {
return title;
}
#Override
public String toString() {
return "Item [id=" + id + ", type=" + type + "]";
}
}
There are also 2 sub classes that extend Item. Those are Book, and CD.
Book:
package org.porthos.concepts.domain;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
#Entity
#Table(name = "book")
#DiscriminatorValue("BOOK")
public class Book extends Item {
#Column(name = "genre")
#Enumerated(EnumType.STRING)
private BookGenre genre;
#Column(name = "title")
private String title;
public static enum BookGenre {
MYSTERY, HISTORY, SCIENCE, COMPUTER;
}
protected Book() {}
public Book(BookGenre genre, String title) {
this.title = title;
this.genre = genre;
this.title = title;
}
public BookGenre getGenre() {
return genre;
}
#Override
public String toString() {
return "Book [genre=" + genre + ", title=" + title + ", getId()=" + getId() + ", getType()="
+ getType() + "]";
}
}
And CD:
package org.porthos.concepts.domain;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
#Entity
#Table(name = "cd")
#DiscriminatorValue("CD")
public class CD extends Item {
#Column(name = "genre")
#Enumerated(EnumType.STRING)
private CDGenre genre;
#Column(name = "title")
private String title;
public static enum CDGenre {
CLASSICAL, POP, ROCK, BLUES;
}
protected CD() {}
public CD(CDGenre genre, String title) {
this.title = title;
this.genre = genre;
this.title = title;
}
public CDGenre getGenre() {
return genre;
}
#Override
public String toString() {
return "CD [genre=" + genre + ", title=" + title + ", getId()=" + getId() + ", getType()="
+ getType() + "]";
}
}
This is the Test class that I am using for testing:
package org.porthos.concepts;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.porthos.concepts.domain.Book;
import org.porthos.concepts.domain.Book.BookGenre;
import org.porthos.concepts.domain.CD;
import org.porthos.concepts.domain.CD.CDGenre;
import org.porthos.concepts.domain.Item;
import org.porthos.concepts.domain.QBook;
import org.porthos.concepts.domain.QItem;
import org.porthos.concepts.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.mysema.query.BooleanBuilder;
import com.mysema.query.types.Predicate;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = ConceptsApplication.class)
#Transactional
public class QueryDslTest {
#Autowired
private ItemRepository itemRepository;
#Before
public void setUp() throws Exception {}
#Test
public void test() {
// Persist a Book and a CD for test
Book book = new Book(BookGenre.SCIENCE, "How To Use Your Microscope");
book = itemRepository.save(book);
CD cd = new CD(CDGenre.BLUES, "The Wind Cries Mary");
cd = itemRepository.save(cd);
Predicate isScienceBook = QItem.item.as(QBook.class).genre.eq(BookGenre.SCIENCE);
BooleanBuilder builder = new BooleanBuilder();
builder.or(isScienceBook);
Page<Item> itemsPage = itemRepository.findAll(builder, new PageRequest(0, 10));
assertThat(itemsPage.getContent().size(), is(1));
}
}
So basically, each of the sub classes Book and CD have a genre property that is Typed differently. The Book genre uses the BookGenre type and the CD genre has the CDGenre type. The problem happens because the properties are named exactly alike.
So when I run the test which is trying to query for a Book, I get the following stack trace which is basically stating that it is expecting genre to be of Type CDGenre.
If I run the test with a query for a CD, the query works without any issues.
Also if I rename the Book and CD genre properties so that they're unique such as bookGenre and cdGenre, then the Book query definitely works.
So in order to use this type of inheritance I have to make sure that each of the sub classes have differently named properties. But in this example a Genre for music CDs should not be the same as a Genre for Books, and I don't see it as necessarily wrong that they're both named genre.
So I'm not sure if it's bad domain design on my part, of if there's an issue with Spring Data JPA, and or QueryDSL.
Thanks,
Frank
Stack trace:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [SCIENCE] did not match expected type [org.porthos.concepts.domain.CD$CDGenre (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [SCIENCE] did not match expected type [org.porthos.concepts.domain.CD$CDGenre (n/a)]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:384)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:436)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy113.findAll(Unknown Source)
at org.porthos.concepts.QueryDslTest.test(QueryDslTest.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalArgumentException: Parameter value [SCIENCE] did not match expected type [org.porthos.concepts.domain.CD$CDGenre (n/a)]
at org.hibernate.jpa.spi.BaseQueryImpl.validateBinding(BaseQueryImpl.java:874)
at org.hibernate.jpa.internal.QueryImpl.access$000(QueryImpl.java:80)
at org.hibernate.jpa.internal.QueryImpl$ParameterRegistrationImpl.bindValue(QueryImpl.java:248)
at org.hibernate.jpa.internal.QueryImpl$JpaPositionalParameterRegistrationImpl.bindValue(QueryImpl.java:337)
at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:674)
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:198)
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:49)
at com.mysema.query.jpa.impl.JPAUtil.setConstants(JPAUtil.java:55)
at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:130)
at com.mysema.query.jpa.impl.AbstractJPAQuery.count(AbstractJPAQuery.java:81)
at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.findAll(QueryDslJpaRepository.java:141)
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.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 38 more
It's all working fine without QueryDSL in a Spring Boot JPA/Web framework, though I had to get rid of the ItemType field in Item since JPA provides that for you.
#Override
public void createBook() {
Book book = new Book(BookGenre.SCIENCE, "How To Use Your Microscope");
bookRepository.save(book);
CD cd = new CD(CDGenre.BLUES, "The Wind Cries Mary");
cdRepository.save(cd);
}
and
#Override
public void getBook() {
Page<Book> books = bookRepository.findByGenre(BookGenre.SCIENCE, new PageRequest(0, 20) );
System.out.println( books.getContent().get(0) );
}
gives
Hibernate: select count(book0_.id) as col_0_0_ from book book0_ inner join item book0_1_ on book0_.id=book0_1_.id where book0_.genre=?
Hibernate: select book0_.id as id2_2_, book0_1_.title as title3_2_, book0_.genre as genre1_0_, book0_.title as title2_0_ from book book0_ inner join item book0_1_ on book0_.id=book0_1_.id where book0_.genre=? limit ?
Book [genre=SCIENCE, title=How To Use Your Microscope, getId()=1]

Composite Key with one Foreign Key OneToMany Spring Boot JPA Informix

This is the current structure of the Informix Database:
Table: msg_body
id (PK)
kanal
sender
...
Table: msg_user
id (PK, FK)
empfaenger (PK)
datum
...
A msg_user has one or more msg_bodies.
msg_body domain class:
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
#Entity
#Table(name="msg_body")
public class MessageBody implements Serializable {
#Id
#Column(name="id")
private int mb_id;
#Column(name="kanal")
private String channel;
#Column(name="gueltig_von")
private Timestamp validFrom;
#Column(name="gueltig_bis")
private Timestamp validTo;
#Column(name="sender")
private String sender;
#Column(name="erstell_datum")
private Timestamp createDate;
#Column(name="prioritaet")
private int priority;
#Column(name="nachricht")
private String message;
#Column(name="info")
private String info;
#Column(name="gueltig")
private char valid;
#ManyToOne
private MessageUser messageUser;
//getter + setter
}
msg_user domain class:
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="msg_user")
public class MessageUser implements Serializable {
#EmbeddedId
UserId mu_id;
#MapsId("mb_id")
#JoinColumn(name = "mu_id", referencedColumnName = "id")
#OneToMany
private Set<MessageBody> msg_bodies = new HashSet<>();
#Column(name = "datum")
private Timestamp receiverDate;
#Column(name = "versuch")
private Timestamp tryTime;
#Column(name = "versuch_anzahl")
private int tryAmount;
#Column(name = "status")
private int state;
#Column(name = "ip")
private char ip;
// getter + setter + hashcode + equals
}
Composite Key Class:
import java.io.Serializable;
import javax.persistence.*;
#Embeddable
public class UserId implements Serializable
{
#Column(name="id")
private int mb_id;
#Column(name="empfaenger")
private String receiver;
// getter + setter + hashcode + equals
}
Application class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#ComponentScan("at.company.badge_service")
#EnableAutoConfiguration
#EnableJpaRepositories(basePackages = {"at.company.badge_service.repository"})
public class Application extends SpringBootServletInitializer
{
public static void main (String[] args)
{
SpringApplication.run(Application.class, args);
}
}
The goal is to run this statement:
public interface BARepository extends JpaRepository<MessageBody, Long>
{
#Query( "SELECT COUNT(mu.id) FROM MessageUser mu WHERE mu.receiver = :username")
Long countBA(#Param("username") String username);
}
application.properties file:
spring.main.show-banner=false
security.basic.enabled=false
spring.thymeleaf.cache=false
# JACKSON
spring.jackson.mapper.default-view-inclusion=true
#spring.jackson.deserialization.fail-on-unknown-properties=false
security.user.name: username
security.user.password: password
spring.view.prefix: /WEB-INF/views/
spring.view.suffix: .jsp
# DATABASE
spring.jpa.database: INFORMIX
spring.jpa.hibernate.ddl-auto: validate
spring.jpa.properties.hibernate.default_batch_fetch_size: 100
spring.datasource.jndi-name=jdbc/msgdb
ErrorCode NullpointerException:
2015-04-24 09:30:04,702 [RMI TCP Connection(3)-127.0.0.1] ERROR o.s.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [na:1.7.0_02]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [na:1.7.0_02]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0_02]
Caused by: java.lang.NullPointerException: null
Apr 24, 2015 9:30:04 AM org.apache.catalina.core.ContainerBase addChildInternal
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1460) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:864) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
Schwerwiegend: ContainerBase.addChild: start:
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:779) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/badge_service]]
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:728) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1426) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:618)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:565)
... 58 common frames omitted
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 40 more
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1460)
at org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:864)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 58 more
Apr 24, 2015 9:30:04 AM org.apache.tomcat.util.modeler.BaseModelMBean invoke
Schwerwiegend: Exception invoking method manageApp
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/badge_service]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:618)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:565)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Apr 24, 2015 9:30:04 AM org.apache.tomcat.util.modeler.BaseModelMBean invoke
Schwerwiegend: Exception invoking method createStandardContext
javax.management.RuntimeOperationsException: Exception invoking method manageApp
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:309)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:791)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:618)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/badge_service]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
... 31 more
I tried to find a solution on the web, but none of them worked in my case. Especially the foreign key in the composite key seems to be a rare problem.
I'm well aware, that it would be much easier to add a surrogate key to the msg_user-table, but I have to solve exactly this problem, so I would be happy if someone could show me how to code the domain classes with the relations in the right way.
If you need further information do not hesitate to ask for them!
Many thanks in advance!
After a while I found myself a solution:
MessageBody domainclass:
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name="msg_body")
public class MessageBody implements Serializable
{
#Id
#Column(name="id")
private int msgb_id;
#Column(name="kanal", columnDefinition = "char")
private String channel;
#Column(name="gueltig_von")
private Timestamp validFrom;
#Column(name="gueltig_bis")
private Timestamp validTo;
#Column(name="sender")
private String sender;
#Column(name="erstell_datum")
private Timestamp createDate;
#Column(name="prioritaet")
private int priority;
#Column(name="nachricht")
private String message;
#Column(name="info", columnDefinition = "lvarchar")
private String info;
#Column(name="gueltig")
private char valid;
#OneToMany
#JoinColumn(name = "id")
private Set<MessageUser> message_users = new HashSet<>();
// getter + setter
}
CompositeKey domainclass:
import java.io.Serializable;
import javax.persistence.*;
#Embeddable
public class MessageUserPK implements Serializable
{
private int mb_id;
private String receiver;
// getter + setter + hashcode + equals
}
MessageUser domainclass:
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.*;
#Entity
#Table(name="msg_user")
public class MessageUser implements Serializable
{
#EmbeddedId
#AttributeOverrides
({
#AttributeOverride(name = "mb_id", column = #Column(name = "id")),
#AttributeOverride(name = "receiver", column = #Column(name = "empfaenger"))
})
MessageUserPK mu_id;
#Column(name = "datum")
private Timestamp receiverDate;
#Column(name = "versuch")
private Timestamp tryTime;
#Column(name = "versuch_anzahl")
private int tryAmount;
#Column(name = "status")
private int state;
#Column(name = "ip")
private char ip;
#ManyToOne
#MapsId("mb_id")
#JoinColumn(name = "id")
private MessageBody messageBody;
// getter + setter + hashcode + equals
}
The relation is bidirectional as in the question, but I put the Collection in the MessageBody-Domainclass. After some other fixes like the "AttributOverrides" it worked. Hope I could help another one with the solution!