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.
Related
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
With Micronaut REST API CRUD operation on table with foreign keys not working
We created a micronaut application with JPA & entity manager. We have table called Employee and State, so we created entity classes for both and referenced state_id in employee table.
With all the implementation we are able to fetch the employee details with state id and name but when we create new employee it is throwing errors.
Employee model:
package io.usermgmt.models;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "employee_id")
private Integer employeeId;
#Column(name = "employee_name")
private String employeeName;
#Column(name = "address")
private String address;
#Column(name = "city")
private String city;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "state_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private State state;
#Column(name = "zip_code")
private String zipCode;
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getAddress(){return address;}
public void setAddress(String address){this.address=address;}
public String getCity(){return city;}
public void setCity(String city){this.city=city;}
public Integer getStateId(){return state.getStateId();}
public String getStateName(){return state.getStateName();}
public String getZipCode(){return zipCode;}
public void setZipCode(String zipCode){this.zipCode=zipCode;}
}
State model:
package io.usermgmt.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Proxy;
import javax.persistence.Column;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "state")
#Proxy(lazy = false)
public class State {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "state_id")
private Integer stateId;
#Column(name = "state_name")
private String stateName;
#OneToMany(mappedBy = "state", fetch = FetchType.LAZY)
#JsonIgnore
private Set<Employee> employees = new HashSet<>();
public Integer getStateId() { return this.stateId; }
public void setStateId(Integer stateId){
this.stateId = stateId;
}
public String getStateName(){ return this.stateName; }
public void setStateName(String stateName){
this.stateName = stateName;
}
}
EmployeeRepositoryImpl
package io.usermgmt.repositories.impl;
import io.usermgmt.models.Client;
import io.usermgmt.repositories.IEmployeeRepository;
import io.micronaut.configuration.hibernate.jpa.scope.CurrentSession;
import io.micronaut.spring.tx.annotation.Transactional;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
#Singleton
public class EmployeeRepositoryImpl implements IEmployeeRepository {
#PersistenceContext
private EntityManager entityManager;
public EmployeeRepositoryImpl(#CurrentSession EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
#Transactional
public Employee createEmployee(#NotNull Employee employee) {
entityManager.persist(employee);
return employee;
}
#Override
#Transactional
public Employee updateEmployee(#NotNull Employee employee) {
return entityManager.merge(employee);
}
#Override
#Transactional(readOnly = true)
public List<Employee> getAllEmployees() {
String qlString = "SELECT c FROM Employee c";
TypedQuery<Employee> query = entityManager.createQuery(qlString, Employee.class);
return query.getResultList();
}
#Override
#Transactional(readOnly = true)
public Optional<Employee> getEmployeeById(#NotNull Integer id) {
return Optional.ofNullable(entityManager.find(Employee.class, id));
}
}
getAllEmployees() is working fine which is getting State details also. But while creating it is below errors.
ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: Error encoding object [io.usermgmt.models.Employee#1d91f388] to JSON: (was j
ava.lang.NullPointerException) (through reference chain: io.usermgmt.models.Employee["stateId"])
io.micronaut.http.codec.CodecException: Error encoding object [io.usermgmt.models.Employee#1d91f388] to JSON: (was java.lang.NullPointerException) (through reference chain: io.app
ter.clientmgmt.models.Employee["stateId"])
at io.micronaut.jackson.codec.JsonMediaTypeCodec.encode(JsonMediaTypeCodec.java:176)
at io.micronaut.jackson.codec.JsonMediaTypeCodec.encode(JsonMediaTypeCodec.java:182)
at io.micronaut.http.server.netty.RoutingInBoundHandler.encodeBodyAsByteBuf(RoutingInBoundHandler.java:1359)
at io.micronaut.http.server.netty.RoutingInBoundHandler.encodeBodyWithCodec(RoutingInBoundHandler.java:1305)
at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$subscribeToResponsePublisher$16(RoutingInBoundHandler.java:1240)
at io.reactivex.internal.operators.flowable.FlowableMap$MapSubscriber.onNext(FlowableMap.java:63)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.lambda$onNext$0(InstrumentedSubscriber.java:80)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.onNext(InstrumentedSubscriber.java:84)
at io.reactivex.internal.operators.flowable.FlowableSwitchMap$SwitchMapSubscriber.drain(FlowableSwitchMap.java:307)
at io.reactivex.internal.operators.flowable.FlowableSwitchMap$SwitchMapInnerSubscriber.onSubscribe(FlowableSwitchMap.java:366)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.onSubscribe(InstrumentedSubscriber.java:75)
at io.reactivex.internal.operators.flowable.FlowableJust.subscribeActual(FlowableJust.java:34)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedCallableFlowable.subscribeActual(RxInstrumentedCallableFlowable.java:65)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.reactivex.internal.operators.flowable.FlowableSwitchMap$SwitchMapSubscriber.onNext(FlowableSwitchMap.java:129)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.lambda$onNext$0(InstrumentedSubscriber.java:80)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.onNext(InstrumentedSubscriber.java:84)
at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.onNext(FlowableSubscribeOn.java:97)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.lambda$onNext$0(InstrumentedSubscriber.java:80)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.onNext(InstrumentedSubscriber.java:84)
at io.micronaut.http.context.ServerRequestTracingPublisher$1.lambda$onNext$1(ServerRequestTracingPublisher.java:60)
at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:52)
at io.micronaut.http.context.ServerRequestTracingPublisher$1.onNext(ServerRequestTracingPublisher.java:60)
at io.micronaut.http.context.ServerRequestTracingPublisher$1.onNext(ServerRequestTracingPublisher.java:52)
at io.reactivex.internal.util.HalfSerializer.onNext(HalfSerializer.java:45)
at io.reactivex.internal.subscribers.StrictSubscriber.onNext(StrictSubscriber.java:97)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.lambda$onNext$0(InstrumentedSubscriber.java:80)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.onNext(InstrumentedSubscriber.java:84)
at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FlowableSwitchIfEmpty.java:59)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.lambda$onNext$0(InstrumentedSubscriber.java:80)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.onNext(InstrumentedSubscriber.java:84)
at io.reactivex.internal.operators.flowable.FlowableMap$MapSubscriber.onNext(FlowableMap.java:68)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.lambda$onNext$0(InstrumentedSubscriber.java:80)
at io.micronaut.reactive.rxjava2.InstrumentedSubscriber.onNext(InstrumentedSubscriber.java:84)
at io.reactivex.internal.operators.flowable.FlowableCreate$NoOverflowBaseAsyncEmitter.onNext(FlowableCreate.java:403)
at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$buildResultEmitter$19(RoutingInBoundHandler.java:1430)
at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:71)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.internal.operators.flowable.FlowableMap.subscribeActual(FlowableMap.java:37)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty.subscribeActual(FlowableSwitchIfEmpty.java:32)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14868)
at io.micronaut.http.context.ServerRequestTracingPublisher.lambda$subscribe$0(ServerRequestTracingPublisher.java:52)
at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:52)
at io.micronaut.http.context.ServerRequestTracingPublisher.subscribe(ServerRequestTracingPublisher.java:52)
at io.reactivex.internal.operators.flowable.FlowableFromPublisher.subscribeActual(FlowableFromPublisher.java:29)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker$BooleanRunnable.run(ExecutorScheduler.java:288)
at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker.run(ExecutorScheduler.java:253)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: io.usermgmt.models.Employee["stateId"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:394)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:353)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:316)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:727)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3905)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsBytes(ObjectMapper.java:3243)
at io.micronaut.jackson.codec.JsonMediaTypeCodec.encode(JsonMediaTypeCodec.java:173)
... 69 common frames omitted
Caused by: java.lang.NullPointerException: null
at io.usermgmt.models.Employee.getStateId(Employee.java:83)
at io.usermgmt.models.$Employee$Introspection$$5.readInternal(Unknown Source)
at io.micronaut.core.beans.AbstractBeanProperty.get(AbstractBeanProperty.java:116)
at io.micronaut.jackson.modules.BeanIntrospectionModule$BeanIntrospectionPropertyWriter.serializeAsField(BeanIntrospectionModule.java:539)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
... 75 common frames omitted
data we are passing through poastman is:
{
"employeeName": "ATT",
"address": "address",
"city": "HYD",
"isActive": true,
"stateId": 1,
"countryName": "India",
"countryId": 2,
"stateName": "telangana"
}
Can anyone help on this please.
This exception:
ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: Error encoding object [io.usermgmt.models.Employee#1d91f388] to JSON: (was java.lang.NullPointerException) (through reference chain: io.usermgmt.models.Employee["stateId"])
Is caused by getStateId() method in Employee class because you have there:
return state.getStateId();
... which must throw NullPointerException because you don't test if state property is null or not and that property is always null because you don't have neither default value nor set method for it.
So change the method in this way for example:
public Integer getStateId() {
return state == null ? null : state.getStateId();
}
The same applies for getStateName() method where is the same problem.
And add also these methods into the Empoyee class to be able to get and set state property value:
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
Correct JSON data structure will be:
{
"employeeName": "ATT",
"address": "address",
"city": "HYD",
"state": {
"stateId": 1,
"stateName": "telangana"},
"zipCode": "zip"
}
Properties isActive, countryName and countryId from your JSON example makes no sense as you don't have them in the Employee entity.
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
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]
I am running a JPA test and I keep getting the error at the end of this post. I have no idea why I'm getting this error, however, I do not get this error when testing in JUnit. I know this is probably a generic message and a broad question but if there's a simple answer, I would appreciate it.
Here are my 3 class files:
package menu.entity;
import static javax.persistence.CascadeType.ALL;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
#IdClass(menu.entity.FeatureKey.class)
#Entity
#Table(name="FEATURES")
public class Feature implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="PROD_ID",
nullable = false,
insertable = false,
updatable = false,
precision=22)
private BigDecimal prodId;
#Id
#Column(name="FEATURE",
nullable = false,
insertable = false,
updatable = false,
precision=22)
private BigDecimal feature;
#Column(name="FEATURE_NAME", length=50)
private String featureName;
#Column(name="FEATURE_PATH", length=100)
private String featurePath;
#OneToMany(cascade=ALL, mappedBy="featureObj")
private List<Function> functions;
#ManyToOne
#JoinColumns({
#JoinColumn(name="PROD_ID", referencedColumnName="PROD_ID")
})
private Product product;
public Feature() {
}
public BigDecimal getFeature() {
return this.feature;
}
public void setFeature(BigDecimal feature) {
this.feature = feature;
}
public String getFeatureName() {
return this.featureName;
}
public void setFeatureName(String featureName) {
this.featureName = featureName;
}
public String getFeaturePath() {
return this.featurePath;
}
public void setFeaturePath(String featurePath) {
this.featurePath = featurePath;
}
public BigDecimal getProdId() {
return this.prodId;
}
public void setProdId(BigDecimal prodId) {
this.prodId = prodId;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public List<Function> getFunctions() {
return functions;
}
public void setFunctions(List<Function> functions) {
this.functions = functions;
}
}
package menu.entity;
import java.math.BigDecimal;
import javax.annotation.Generated;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="Dali", date="2012-10-01T17:03:26.750-0400")
#StaticMetamodel(Feature.class)
public class Feature_ {
public static volatile SingularAttribute<Feature, BigDecimal> prodId;
public static volatile SingularAttribute<Feature, BigDecimal> feature;
public static volatile SingularAttribute<Feature, String> featureName;
public static volatile SingularAttribute<Feature, String> featurePath;
public static volatile ListAttribute<Feature, Function> functions;
public static volatile SingularAttribute<Feature, Product> product;
}
package menu.entity;
import static javax.persistence.CascadeType.ALL;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
#IdClass(menu.entity.FunctionKey.class)
#Entity
#Table(name="FUNCTIONS")
public class Function implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="PROD_ID",
nullable = false,
insertable = false,
updatable = false,
precision=22)
private BigDecimal prodId;
#Id
#Column(name="FEATURE",
nullable = false,
insertable = false,
updatable = false,
precision=22)
private BigDecimal feature;
#Id
#Column(name="FUNC",
nullable = false,
insertable = false,
updatable = false,
precision=22)
private BigDecimal func;
#Column(name="FUNC_NAME", length=50)
private String funcName;
#Column(name="FUNC_PATH", length=80)
private String funcPath;
#OneToMany(cascade=ALL, mappedBy="function")
private List<Task> tasks;
#ManyToOne
#JoinColumns({
#JoinColumn(name="PROD_ID", referencedColumnName="PROD_ID"),
#JoinColumn(name="FEATURE", referencedColumnName="FEATURE")
})
private Feature featureObj;
public Function() {
}
public BigDecimal getFeature() {
return this.feature;
}
public void setFeature(BigDecimal feature) {
this.feature = feature;
}
public BigDecimal getFunc() {
return func;
}
public void setFunc(BigDecimal func) {
this.func = func;
}
public String getFuncName() {
return this.funcName;
}
public void setFuncName(String funcName) {
this.funcName = funcName;
}
public String getFuncPath() {
return this.funcPath;
}
public void setFuncPath(String funcPath) {
this.funcPath = funcPath;
}
public BigDecimal getProdId() {
return this.prodId;
}
public void setProdId(BigDecimal prodId) {
this.prodId = prodId;
}
public Feature getFeatureObj() {
return featureObj;
}
public void setFeatureObj(Feature featureObj) {
this.featureObj = featureObj;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
}
Regards,
Paul
Here is the full stack trace:
java.lang.IllegalArgumentException: Attribute "functions" of any not
found in menu.entity.Feature at
org.apache.openjpa.persistence.meta.AbstractManagedType.notFoundException(AbstractManagedType.java:734)
at
org.apache.openjpa.persistence.meta.AbstractManagedType.getAttribute(AbstractManagedType.java:237)
at
org.apache.openjpa.persistence.meta.AbstractManagedType.getAttribute(AbstractManagedType.java:461)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.populate(MetamodelImpl.java:311)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.instantiate(MetamodelImpl.java:257)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.find(MetamodelImpl.java:226)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.(MetamodelImpl.java:91)
at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.getMetamodel(EntityManagerFactoryImpl.java:346)
at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.getCriteriaBuilder(EntityManagerFactoryImpl.java:333)
at
org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:1649)
at
org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:101)
at menu.ejb.RequestBean.init(RequestBean.java:60) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:267)
at
org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
at
org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
at
org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:263)
at
org.jboss.weld.introspector.jlr.WeldMethodImpl.invoke(WeldMethodImpl.java:174)
at
org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:398)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.postConstruct(ManagedBean.java:174)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:294) at
org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:68)
at
org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:599)
at
org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:665)
at
org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:136)
at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:686) at
org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:695)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:161)
at
org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:48)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:157)
at
org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:131)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:153)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:293) at
org.jboss.weld.context.AbstractContext.get(AbstractContext.java:103)
at
org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:90)
at
org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:79)
at
menu.web.MenuManager$Proxy$_$$WeldClientProxy.getMenuItemsS(MenuManager$Proxy$$$_WeldClientProxy.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
javax.el.BeanELResolver.getValue(BeanELResolver.java:87) at
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169) at
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at
org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169) at
com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662) Oct 2, 2012 12:50:22 PM
com.sun.faces.application.view.FaceletViewHandlingStrategy
handleRenderException SEVERE: Error Rendering View[/menu.xhtml]
javax.el.ELException: /menu.xhtml #26,51
value="#{menuManager.menuItemsS}": Error reading 'menuItemsS' on type
menu.web.MenuManager$Proxy$_$$_WeldClientProxy at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169) at
com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662) Caused by:
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke
[method] #PostConstruct private menu.ejb.RequestBean.init() on
menu.ejb.RequestBean#19ca9ff at
org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:400)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.postConstruct(ManagedBean.java:174)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:294) at
org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:68)
at
org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:599)
at
org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:665)
at
org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:136)
at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:686) at
org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:695)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:161)
at
org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:48)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:157)
at
org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:131)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:153)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:293) at
org.jboss.weld.context.AbstractContext.get(AbstractContext.java:103)
at
org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:90)
at
org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:79)
at
menu.web.MenuManager$Proxy$_$$WeldClientProxy.getMenuItemsS(MenuManager$Proxy$$$_WeldClientProxy.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
javax.el.BeanELResolver.getValue(BeanELResolver.java:87) at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:176)
at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169) at
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at
org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
... 34 more Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:267)
at
org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
at
org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
at
org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:263)
at
org.jboss.weld.introspector.jlr.WeldMethodImpl.invoke(WeldMethodImpl.java:174)
at
org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:398)
... 63 more Caused by: java.lang.RuntimeException: public static
volatile javax.persistence.metamodel.ListAttribute
menu.entity.Feature.functions at
org.apache.openjpa.persistence.meta.MetamodelImpl.populate(MetamodelImpl.java:330)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.instantiate(MetamodelImpl.java:257)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.find(MetamodelImpl.java:226)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.(MetamodelImpl.java:91)
at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.getMetamodel(EntityManagerFactoryImpl.java:346)
at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.getCriteriaBuilder(EntityManagerFactoryImpl.java:333)
at
org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:1649)
at
org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:101)
at menu.ejb.RequestBean.init(RequestBean.java:60) ... 73 more Oct 2,
2012 12:50:22 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with
path [/jsfCDITest] threw exception [WELD-000049 Unable to invoke
[method] #PostConstruct private menu.ejb.RequestBean.init() on
menu.ejb.RequestBean#19ca9ff] with root cause
java.lang.RuntimeException: public static volatile
javax.persistence.metamodel.ListAttribute
menu.entity.Feature_.functions at
org.apache.openjpa.persistence.meta.MetamodelImpl.populate(MetamodelImpl.java:330)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.instantiate(MetamodelImpl.java:257)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.find(MetamodelImpl.java:226)
at
org.apache.openjpa.persistence.meta.MetamodelImpl.(MetamodelImpl.java:91)
at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.getMetamodel(EntityManagerFactoryImpl.java:346)
at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.getCriteriaBuilder(EntityManagerFactoryImpl.java:333)
at
org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:1649)
at
org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:101)
at menu.ejb.RequestBean.init(RequestBean.java:60) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:267)
at
org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
at
org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
at
org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:263)
at
org.jboss.weld.introspector.jlr.WeldMethodImpl.invoke(WeldMethodImpl.java:174)
at
org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:398)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.postConstruct(ManagedBean.java:174)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:294) at
org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:68)
at
org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:599)
at
org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:665)
at
org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:136)
at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:686) at
org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:695)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:161)
at
org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:48)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:157)
at
org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:131)
at
org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:153)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:293) at
org.jboss.weld.context.AbstractContext.get(AbstractContext.java:103)
at
org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:90)
at
org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:79)
at
menu.web.MenuManager$Proxy$_$$WeldClientProxy.getMenuItemsS(MenuManager$Proxy$$$_WeldClientProxy.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
javax.el.BeanELResolver.getValue(BeanELResolver.java:87) at
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169) at
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at
org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169) at
com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
I believe that RuntimeException is thrown because another exception occurred. That other exception's stack trace should be printed to the console.