java.sql.SQLException: Field 'userid' doesn't have a default value? - spring

when I try to test post method on postman, I got the following error. Please help me with it.
userController
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDto;
import com.appsdeveloperblog.app.ws.ui.model.request.UserDetailsRequestModel;
import com.appsdeveloperblog.app.ws.ui.model.response.UserRest;
#RestController
#RequestMapping("users") // http://localhost:8080/users
public class UserController {
#Autowired
UserService userService;
#GetMapping
public String getUser() {
return "get...";
}
#PostMapping
public UserRest createUser(#RequestBody UserDetailsRequestModel userDetails) {
UserRest returnValue = new UserRest();
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userDetails, userDto);
UserDto createdUser = userService.createUser(userDto);
BeanUtils.copyProperties(createdUser, returnValue);
return returnValue;
}
#PutMapping
public String updateUser() {
return "update...";
}
#DeleteMapping
public String deleteUser() {
return "delete....";
}
}
UserDetailsRequestModel
public class UserDetailsRequestModel {
private String firstName;
private String lastName;
private String email;
private String password;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserRest
public class UserRest {
private String userId;
private String firstName;
private String lastName;
private String email;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserDto
import java.io.Serializable;
public class UserDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8218131459558712226L;
private long id;
private String userId;
private String firstName;
private String lastName;
private String email;
private String password;
private String encryptedPassword;
private String emailVerificationToken;
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
UserServiceImpl
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.appsdeveloperblog.app.ws.UserRepository;
import com.appsdeveloperblog.app.ws.io.entity.UserEntity;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDto;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserRepository userRepository;
#Override
public UserDto createUser(UserDto user) {
UserEntity userEntity = new UserEntity();
BeanUtils.copyProperties(user, userEntity);
userEntity.setEncryptedPassword("test");
userEntity.setUserId("testUserId");
UserEntity storedUserDetails = userRepository.save(userEntity);
UserDto returnValue = new UserDto();
BeanUtils.copyProperties(storedUserDetails, returnValue);
return returnValue;
}
}
UserEntity
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "users")
public class UserEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5313493413859894403L;
#Id
#GeneratedValue
private long id;
#Column(nullable = false)
private String userId;
#Column(nullable = false, length = 50)
private String firstName;
#Column(nullable = false, length = 50)
private String lastName;
#Column(nullable = false, length = 120)
private String email;
#Column(nullable = false)
private String encryptedPassword;
private String emailVerificationToken;
#Column(nullable = false)
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
Error
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.0.RELEASE)
2020-06-10 15:21:45.653 INFO 72682 --- [ main] c.a.app.ws.MobileAppWsApplication : Starting MobileAppWsApplication on Mings-MBP with PID 72682 (/Users/mingwang/Workspaces/workspace-spring-tool-suite-4-4.6.2.RELEASE/mobile-app-ws/target/classes started by mingwang in /Users/mingwang/Workspaces/workspace-spring-tool-suite-4-4.6.2.RELEASE/mobile-app-ws)
2020-06-10 15:21:45.656 INFO 72682 --- [ main] c.a.app.ws.MobileAppWsApplication : No active profile set, falling back to default profiles: default
2020-06-10 15:21:46.381 INFO 72682 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-06-10 15:21:46.465 INFO 72682 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 70ms. Found 1 JPA repository interfaces.
2020-06-10 15:21:47.011 INFO 72682 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-06-10 15:21:47.022 INFO 72682 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-06-10 15:21:47.022 INFO 72682 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-06-10 15:21:47.119 INFO 72682 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-06-10 15:21:47.119 INFO 72682 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1426 ms
2020-06-10 15:21:47.326 INFO 72682 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-06-10 15:21:47.368 INFO 72682 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-06-10 15:21:47.423 WARN 72682 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-06-10 15:21:47.492 INFO 72682 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
2020-06-10 15:21:47.684 INFO 72682 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-06-10 15:21:47.787 INFO 72682 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-06-10 15:21:48.180 INFO 72682 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-06-10 15:21:48.202 INFO 72682 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-06-10 15:21:49.032 INFO 72682 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-06-10 15:21:49.039 INFO 72682 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-06-10 15:21:49.555 INFO 72682 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-06-10 15:21:49.556 INFO 72682 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-06-10 15:21:49.589 INFO 72682 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-06-10 15:21:49.599 INFO 72682 --- [ main] c.a.app.ws.MobileAppWsApplication : Started MobileAppWsApplication in 4.303 seconds (JVM running for 4.953)
2020-06-10 15:21:56.900 INFO 72682 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-06-10 15:21:56.900 INFO 72682 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-06-10 15:21:56.911 INFO 72682 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 10 ms
2020-06-10 15:21:57.243 WARN 72682 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
2020-06-10 15:21:57.243 ERROR 72682 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'userid' doesn't have a default value
2020-06-10 15:21:57.293 ERROR 72682 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'userid' doesn't have a default value
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3235) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3760) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:na]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1352) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:631) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:385) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.sun.proxy.$Proxy88.save(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.sun.proxy.$Proxy60.save(Unknown Source) ~[na:na]
at com.appsdeveloperblog.app.ws.service.impl.UserServiceImpl.createUser(UserServiceImpl.java:28) ~[classes/:na]
at com.appsdeveloperblog.app.ws.ui.controller.UserController.createUser(UserController.java:38) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.35.jar:9.0.35]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Debug
I tried to debug it. It seemed I set userId successfully.
I know pics are annoying, but I don't know how to show my debug process in other way.
Debug process:
enter image description here
enter image description here

Hibernate
Hibernate is the interface/link/glue/middleware between your application and the database. It's one of the many framework/libraries, out there, that is making ORM possible and easy. Keyword here is easy, as it makes our lives really simple!
The idea behind Hibernate's naming strategies is to map your POJO(class/model), in your case UserEntity to its respective physical(actual) DB table as seamless as possible(magical, if you will). So, if you name your logical field userId in your POJO, Hibernate needs to be able to map it to the respective physical table column name, example user_id.
Hibernate naming strategies
If you do not explicitly specify the column name(i.e #Column(name = "userid"), Hibernate determines a proper logical name defined by the ImplicitNamingStrategy. If you choose the default/jpa strategy, for basic attributes, it uses the name of the attributes as the logical name. Ideally, all you have to do is:
#Column
private String userId;
So userId is mapped logically to userId implicitly. It further resolves this proper logical name to a physical name, defined by the PhysicalNamingStrategy. By default, Hibernate uses the logical name as the physical name, but the real purpose of the PhysicalNamingStrategy is to say that physical column userId is actually abbreviated to user_id.
Spring Boot
The good news is that Spring Boot provides defaults for both strategies:
spring.jpa.hibernate.naming.physical-strategy defaults to
org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
spring.jpa.hibernate.naming.implicit-strategy defaults to
org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
By default, Spring Boot configures the physical naming strategy with CamelCaseToUnderscoresNamingStrategy, this strategy will:
-Change camel-case to snake case(Good if your DB users table column name is user_id.
-Replace dots with underscores.
-Lower-case table names, but it is possible to override that flag if your schema requires it.
You could explicitly(it's Spring Boot's default) add it as a Hibernate property:
#Configuration
public class HibernateConfiguration {
Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setJpaProperties(hibernateProperties());
Or choose the strategy that best match your use-case. This and this are excellent to learn more about naming strategies.
Easy, long-winded, but clear
The easiest, although not recommended, unless you have no choice(Will you be doing this for all the attributes of all your #Entity classes?), would be to explicitly defined the actual table's column name, in your UserEntity class:
#Column(name = "userid")
private String userId;
How should you name your columns?
Fabricio mentions this: Better yet if you follow the convention of using underscore separated names for your db columns(i.e snake-case) and camel case names for your Java entity properties. This is also Spring conventions:
#Column
private String userId;
DEBUG
During development, you can turn on debugging to see what's really going on by adding this in your application.properties:
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
spring.jpa.properties.hibernate.format_sql=true
EDIT:
The main issue was that the column was set to #Column(nullable = false), but i will leave all the notes above as it's informative.

Unless you are using a custom PhysicalNamingStrategy, your property userId name does not match your column userid. Column and table name are case sensitive in MySQL on Linux-based environments.
You can map your property to a different column name using #Column(name = "userid"). Better yet if you follow the convention of using underscore separated names for your db columns and camel case names for your Java entity properties.

Related

Caused by: org.hibernate.QueryException:illegal attempt to dereference collection[office0_.officeCode.employees]with element property reference firstN

I am working on Spring Boot and Spring Data JPA and writing JPQL queries. I want to convert below SubQuery into JPQL, but I'm getting below error.
Error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootJpaMysqlComplexApplication': Unsatisfied dependency expressed through field 'officeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'officeRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.repository.OfficeRepository.findByEmployeesAndOfficeCode()!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
at com.example.SpringBootJpaMysqlComplexApplication.main(SpringBootJpaMysqlComplexApplication.java:24) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'officeRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.repository.OfficeRepository.findByEmployeesAndOfficeCode()!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
... 19 common frames omitted
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.repository.OfficeRepository.findByEmployeesAndOfficeCode()!
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:63) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:142) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:209) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:574) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:567) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_171]
at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_171]
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049) ~[na:1.8.0_171]
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:1.8.0_171]
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_171]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_171]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_171]
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_171]
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_171]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:569) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:559) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at java.util.Optional.map(Optional.java:215) ~[na:1.8.0_171]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:559) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:332) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:300) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:121) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
... 29 common frames omitted
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: illegal attempt to dereference collection [office0_.officeCode.employees] with element property reference [firstName] [SELECT o.employees.firstName, o.employees.lastName FROM com.example.entity.Office o WHERE o.country='USA']
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:718) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:368) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at com.sun.proxy.$Proxy89.createQuery(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
... 58 common frames omitted
Caused by: org.hibernate.QueryException: illegal attempt to dereference collection [office0_.officeCode.employees] with element property reference [firstName] [SELECT o.employees.firstName, o.employees.lastName FROM com.example.entity.Office o WHERE o.country='USA']
at org.hibernate.QueryException.generateQueryException(QueryException.java:120) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:155) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:600) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:709) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
... 65 common frames omitted
Caused by: org.hibernate.QueryException: illegal attempt to dereference collection [office0_.officeCode.employees] with element property reference [firstName]
at org.hibernate.hql.internal.ast.tree.DotNode$1.buildIllegalCollectionDereferenceException(DotNode.java:59) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.tree.DotNode.checkLhsIsNotCollection(DotNode.java:643) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:252) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:114) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:109) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:104) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.tree.DotNode.resolveSelectExpression(DotNode.java:786) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.HqlSqlWalker.resolveSelectExpression(HqlSqlWalker.java:1057) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2295) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2232) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1503) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:585) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:272) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
... 71 common frames omitted
Query:
SELECT
lastName, firstName
FROM
employees
WHERE
officeCode IN (SELECT
officeCode
FROM
offices
WHERE
country = 'USA');
Repository - I want to make the use of object graph, as entities are associated with each other would certainly get the data.
public interface OfficeRepository extends JpaRepository<Office, String>{
#Query("SELECT o.employees.firstName, o.employees.lastName FROM Office o WHERE o.country='USA'")
List<Object[]> findByEmployeesAndOfficeCode();
}
Entity - Office:
#Entity
#Table(name="offices")
#NamedQuery(name="Office.findAll", query="SELECT o FROM Office o")
public class Office implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(unique=true, nullable=false, length=10)
private String officeCode;
#Column(nullable=false, length=50)
private String addressLine1;
#Column(length=50)
private String addressLine2;
#Column(nullable=false, length=50)
private String city;
#Column(nullable=false, length=50)
private String country;
#Column(nullable=false, length=50)
private String phone;
#Column(nullable=false, length=15)
private String postalCode;
#Column(length=50)
private String state;
#Column(nullable=false, length=10)
private String territory;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="office")
private List<Employee> employees;
public Office() {
}
public String getOfficeCode() {
return this.officeCode;
}
public void setOfficeCode(String officeCode) {
this.officeCode = officeCode;
}
public String getAddressLine1() {
return this.addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return this.addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPostalCode() {
return this.postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getTerritory() {
return this.territory;
}
public void setTerritory(String territory) {
this.territory = territory;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setOffice(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setOffice(null);
return employee;
}
}
Entity - Employee:
#Entity
#Table(name="employees")
#NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(unique=true, nullable=false)
private int employeeNumber;
#Column(nullable=false, length=100)
private String email;
#Column(nullable=false, length=10)
private String extension;
#Column(nullable=false, length=50)
private String firstName;
#Column(nullable=false, length=50)
private String jobTitle;
#Column(nullable=false, length=50)
private String lastName;
//bi-directional many-to-one association to Customer
#OneToMany(mappedBy="employee")
private List<Customer> customers;
//bi-directional many-to-one association to Employee
#ManyToOne
#JoinColumn(name="reportsTo")
private Employee employee;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="employee")
private List<Employee> employees;
//bi-directional many-to-one association to Office
#ManyToOne
#JoinColumn(name="officeCode", nullable=false)
private Office office;
public Employee() {
}
public int getEmployeeNumber() {
return this.employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExtension() {
return this.extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Customer> getCustomers() {
return this.customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
public Customer addCustomer(Customer customer) {
getCustomers().add(customer);
customer.setEmployee(this);
return customer;
}
public Customer removeCustomer(Customer customer) {
getCustomers().remove(customer);
customer.setEmployee(null);
return customer;
}
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setEmployee(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setEmployee(null);
return employee;
}
public Office getOffice() {
return this.office;
}
public void setOffice(Office office) {
this.office = office;
}
}
After getting idea from #arjun - I make my query like below.
#Query("SELECT e.firstName, e.lastName FROM Office o JOIN o.employees e WHERE o.country='USA'")
List<Object[]> findByEmployeesAndOfficeCode();
Console shows:
select
employees1_.firstName as col_0_0_,
employees1_.lastName as col_1_0_
from
offices office0_
inner join
employees employees1_
on office0_.officeCode=employees1_.officeCode
where
office0_.country='USA';
I hope this is correct way to implement sub-queries in JPQL.
There is one to many mapping between office and employee, you need to try join in your #query tag query some thing like this
SELECT e.firstName, e.lastName FROM Office o join employees e WHERE o.officeId =e.office Id and o.country='USA'
please make sure you are joining on primary key or index column.

How to inject Values into a Null Object Using #Autowired in Spring IOC?

I just started working on a Spring Rest Application, currently I am managing the authentication operations, what I want to do is to Simply check if the typed email address is already used, the problem is that when It doesn't exist I can't autowire the bean User I get a NullPointerException.
I found similar questions in SOF but my code seems to be correct, please Help.
Here is My Code :
Project Architecture
User.java:
#Component
#Entity
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="idUser", scope = User.class)
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idUser;
#Column(name = "login", unique = true)
private String login;
private String password;
private String nom;
private String prenom;
private String email;
private long telephone;
private String statut;
private int isDeleted;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(fetch = FetchType.LAZY)
private Role userRole;
public User(Long idUser, String login, String password, String nom, String prenom, String email,
long telephone, String statut, int isDeleted, Role userRole) {
super();
this.idUser = idUser;
this.login = login;
this.password = password;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.telephone = telephone;
this.statut = statut;
this.isDeleted = isDeleted;
this.userRole = userRole;
}
public User() {
super();
}
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getTelephone() {
return telephone;
}
public void setTelephone(long telephone) {
this.telephone = telephone;
}
public String getStatut() {
return statut;
}
public void setStatut(String statut) {
this.statut = statut;
}
public int getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(int isDeleted) {
this.isDeleted = isDeleted;
}
public Role getUserRole() {
return userRole;
}
public void setUserRole(Role userRole) {
this.userRole = userRole;
}}
UserRepository.java:
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByLoginLikeAndPasswordLikeAndIsDeletedEquals(String login, String password, int i);
User findByLoginLike(String login);
}
UserDTO.java
#Component
public class UserDTO {
private Long idUser;
private String login;
private String password;
private String role ;
public UserDTO(Long idUser, String login, String password, String role) {
super();
this.idUser = idUser;
this.login = login;
this.password = password;
this.role = role;
}
public UserDTO() {
super();
}
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserService.java :
#Service
public class UserService {
#Autowired
private UserDTO userDto;
#Autowired
private User user;
#Autowired
private UserRepository userRep;
#Autowired
private RoleRepository roleRep;
public boolean addUser(String login, String password, String role) {
boolean state = false;
try {
System.out.println(user.toString());
user = userRep.findByLoginLike(login);
if (user == null) {
user.setPassword(password);
user.setLogin(login);
user.setUserRole(roleRep.findByNomRoleLike(role));
userRep.save(user);
state = true;
} else {
System.out.println("user already exists");
state = false;
}
} catch (Exception e) {
e.printStackTrace();
state = false;
}
return state;
}
UserController.java
#RestController
public class UserControler {
#Autowired
private User user;
#Autowired
private UserRepository userRep;
#Autowired
private List<User> allUsers;
#Autowired
private UserService userService;
#Autowired
private UserDTO userDTO;
#RequestMapping( value = "/addUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Boolean addUser(#RequestBody UserDTO u){
boolean state = false;
try {
state = userService.addUser(u.getLogin(), u.getPassword(), "Administrateur");
} catch (Exception e) {
e.printStackTrace();
}
return state;
}
StackTrace :
Hibernate: select users0_.user_role_id_role as user_ro10_1_0_,
users0_.id_user as id_user1_1_0_, users0_.id_user as id_user1_1_1_,
users0_.email as email2_1_1_, users0_.is_deleted as is_delet3_1_1_,
users0_.login as login4_1_1_, users0_.nom as nom5_1_1_,
users0_.password as password6_1_1_, users0_.prenom as prenom7_1_1_,
users0_.statut as statut8_1_1_, users0_.telephone as telephon9_1_1_,
users0_.user_role_id_role as user_ro10_1_1_ from user users0_ where
users0_.user_role_id_role=? 2018-12-20 14:25:58.061 TRACE 6192 ---
[nio-8080-exec-5] o.h.type.descriptor.sql.BasicBinder : binding
parameter 1 as [BIGINT] - [3] 2018-12-20 14:26:36.015 WARN 6192 ---
[nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
exception caused by handler execution:
org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'POST' not supported
java.lang.NullPointerException at
com.akkaprofil.service.UserService.addUser(UserService.java:63) at
com.akkaprofil.controller.UserControler.addUser(UserControler.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:849)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:760)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
When I call the AddUser Request method, this Exception is triggered, I can't find the reason why values are not set to the user Object when the email adress is not found, All the classes are annotated woth their Stereotypes, the user
Bean is autowired, I haven't declared a new Operator.
Would you clarify the cause behind this Exception.
Thank you

jpa Many to many with extra columns : column id cannot be null

I'm trying to save a Entity with relationship many to many with extra column but I've received an error
Item :
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id ;
private String name ;
private String brand ;
private String category ;
private Double unitPrice ;
private Double weight ;
private String manufacturer ;
private String description ;
#OneToMany(mappedBy = "item", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ItemInventory> itemInventories;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Double unitPrice) {
this.unitPrice = unitPrice;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Item() {
super();
// TODO Auto-generated constructor stub
}
public Set<ItemInventory> getItemInventories() {
return itemInventories;
}
public void setItemInventories(Set<ItemInventory> itemInventories) {
this.itemInventories = itemInventories;
}
public Item(Integer id, String name, String brand, String category, Double unitPrice, Double weight,
String manufacturer, String description, Set<ItemInventory> itemInventories) {
super();
this.id = id;
this.name = name;
this.brand = brand;
this.category = category;
this.unitPrice = unitPrice;
this.weight = weight;
this.manufacturer = manufacturer;
this.description = description;
this.itemInventories = itemInventories;
}
#Override
public String toString() {
return "Item [id=" + id + "]";
}
}
Inventory :
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
#Entity
public class Inventory {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String address ;
private String phone ;
#Override
public String toString() {
return "Inventory [id=" + id + "]";
}
private String gps_coordinates ;
#ManyToOne
#JoinColumn(name = "company_id")
private Company company ;
#OneToMany(mappedBy = "inventory", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ItemInventory> itemInventories;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getGps_coordinates() {
return gps_coordinates;
}
public void setGps_coordinates(String gps_coordinates) {
this.gps_coordinates = gps_coordinates;
}
public Set<ItemInventory> getItemInventories() {
return itemInventories;
}
public void setItemInventories(Set<ItemInventory> itemInventories) {
this.itemInventories = itemInventories;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Inventory(Integer id, String address, String phone, String gps_coordinates, Company company,
Set<ItemInventory> itemInventories) {
super();
this.id = id;
this.address = address;
this.phone = phone;
this.gps_coordinates = gps_coordinates;
this.company = company;
this.itemInventories = itemInventories;
}
public Inventory() {
super();
// TODO Auto-generated constructor stub
}
}
ItemInventory :
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
#Entity
#Table(name = "item_inventory")
public class ItemInventory implements Serializable {
#Id
#ManyToOne
#JoinColumn(name = "item_id")
private Item item ;
#Id
#ManyToOne
#JoinColumn(name = "inventory_id")
private Inventory inventory ;
private Long quantity ;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
#Column(name = "quantity")
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public ItemInventory(Item item, Inventory inventory, Long quantity) {
super();
this.item = item;
this.inventory = inventory;
this.quantity = quantity;
}
public ItemInventory() {
super();
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return "ItemInventory [item=" + item + ", inventory=" + inventory + ", quantity=" + quantity + "]";
}
}
The stack trace :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'item_id' cannot be null at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
~[na:1.8.0_112] at
sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
~[na:1.8.0_112] at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
Source) ~[na:1.8.0_112] at
java.lang.reflect.Constructor.newInstance(Unknown Source)
~[na:1.8.0_112] at
com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.Util.getInstance(Util.java:408)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2494)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
~[mysql-connector-java-5.1.43.jar:5.1.43] at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
~[na:1.8.0_112] at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
~[na:1.8.0_112] at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
~[na:1.8.0_112] at java.lang.reflect.Method.invoke(Unknown Source)
~[na:1.8.0_112] at
org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
~[tomcat-jdbc-8.5.16.jar:na] at
com.sun.proxy.$Proxy104.executeUpdate(Unknown Source) ~[na:na] at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2949)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3449)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:582)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:456)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1282)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:465)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2963)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2339)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:61)
~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] at
org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
~[spring-tx-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
~[spring-tx-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
~[spring-tx-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
~[spring-tx-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
~[spring-tx-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
~[spring-aop-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
~[spring-tx-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
~[spring-aop-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
~[spring-data-jpa-1.11.6.RELEASE.jar:na] at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
~[spring-aop-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
~[spring-aop-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
~[spring-aop-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
~[spring-data-commons-1.13.6.RELEASE.jar:na] at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
~[spring-aop-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
~[spring-aop-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
com.sun.proxy.$Proxy92.save(Unknown Source) ~[na:na] at
com.inconso.companyManagement.ItemController.addItem(ItemController.java:38)
~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:1.8.0_112] at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
~[na:1.8.0_112] at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
~[na:1.8.0_112] at java.lang.reflect.Method.invoke(Unknown Source)
~[na:1.8.0_112] at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
~[tomcat-embed-websocket-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
~[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
[tomcat-embed-core-8.5.16.jar:8.5.16] at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
[na:1.8.0_112] at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
[na:1.8.0_112] at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
[tomcat-embed-core-8.5.16.jar:8.5.16] at java.lang.Thread.run(Unknown
Source) [na:1.8.0_112]
Here is my controller :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.inconso.models.Inventory;
import com.inconso.models.Item;
import com.inconso.models.ItemInventory;
import com.inconso.repositories.InventoryRepository;
import com.inconso.repositories.ItemRepository;
#RestController
public class ItemController {
#Autowired
private ItemRepository itemRepos ;
#Autowired
private InventoryRepository inventoryRepos ;
#RequestMapping(value = "itemInventory/add/{company}", method = RequestMethod.POST)
public Object addItem(#RequestBody ItemInventory itemInventory) {
Item item = itemRepos.findOne(itemInventory.getItem().getId()) ;
// still add stuff here in case item not found
Inventory inventory = inventoryRepos.findOne(itemInventory.getInventory().getId()) ;
// still add stuff here if inventory not found
itemInventory.setInventory(inventory);
itemInventory.setItem(item);
item.getItemInventories().add(itemInventory) ;
inventory.getItemInventories().add(itemInventory) ;
System.out.println("-------"+itemInventory.getItem()+"---------");
itemRepos.save(item) ;
return "Item added" ;
}
}
I removed this line
item.getItemInventories().add(itemInventory) ;
and it worked, I think because inventory is the owner of the realtionship, so we should add the itemInventory object to inventory only not both (item and inventory)

PersistentObjectException: Uninitialized proxy passed to persist

I am working with Spring Data JPA and an MySQL database for a records management system. Below are two entities that I have modeled and I am trying to persist a Policy record to the database:
Policy Entity:
public class Policy {
private String policyNumber;
private String policyName;
private Steward steward;
private PolicyHolder policyHolder;
#Id
#Column(length = 30)
public String getPolicyNumber() {
return policyNumber;
}
public void setPolicyNumber(String policyNumber) {
this.policyNumber = policyNumber;
}
#Column(length = 80)
public String getPolicyName() {
return policyName;
}
public void setPolicyName(String policyName) {
this.policyName = policyName;
}
#OneToOne(cascade = ALL, mappedBy = "policy", orphanRemoval = true, optional = false)
public PolicyHolder getPolicyHolder() {
return policyHolder;
}
}
PolicyHolder Entity:
#Entity
public class PolicyHolder extends PolicyMember {
private Policy policy;
public PolicyHolder() {
super();
}
#OneToOne
#JoinColumn(name = "policy_policyNumber", referencedColumnName = "policyNumber")
public Policy getPolicy() {
return policy;
}
public void setPolicy(Policy policy) {
this.policy = policy;
}
#Override
public String toString() {
return "PolicyHolder{" +
"policy=" + policy +
"} " + super.toString();
}
}
PolicyMember Entity:
#Entity
public abstract class PolicyMember {
private CompositePolicyMemberPK policyMemberId;
private String firstname;
private String surname;
private LocalDate dateOfDeath;
private LocalDate dateOfBirth;
private MemberStatus status;
private BillingStatus billingStatus;
private String nationalId;
private LocalDateTime creationDate;
private Gender gender;
private String msisdn;
private LocalDate closureDate;
private String createdBy;
private String memberType;
private PackageBenefit packageBenefit;
private List<DependantTransferRequest> transferRequests;
#EmbeddedId
public CompositePolicyMemberPK getPolicyMemberId() {
return policyMemberId;
}
public void setPolicyMemberId(CompositePolicyMemberPK policyMemberId) {
this.policyMemberId = policyMemberId;
}
#Column(length = 50)
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(length = 50)
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Convert(converter = MemberStatusConverter.class)
public MemberStatus getStatus() {
return status;
}
public void setStatus(MemberStatus status) {
this.status = status;
}
#Convert(converter = BillingStatusConverter.class)
public BillingStatus getBillingStatus() {
return billingStatus;
}
public void setBillingStatus(BillingStatus billingStatus) {
this.billingStatus = billingStatus;
}
#Column(length = 20)
public String getNationalId() {
return nationalId;
}
public void setNationalId(String nationalId) {
this.nationalId = nationalId;
}
#Enumerated(EnumType.STRING)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
#Column(length = 15)
public String getMsisdn() {
return msisdn;
}
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
#Column(length = 50)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "memberType", insertable = false, updatable = false)
public String getMemberType() {
return memberType;
}
public void setMemberType(String memberType) {
this.memberType = memberType;
}
#OneToOne(mappedBy = "policyMember", optional = false, cascade = CascadeType.ALL)
public PackageBenefit getPackageBenefit() {
return packageBenefit;
}
public void setPackageBenefit(PackageBenefit packageBenefit) {
this.packageBenefit = packageBenefit;
}
public LocalDate getDateOfDeath() {
return dateOfDeath;
}
public void setDateOfDeath(LocalDate dateOfDeath) {
this.dateOfDeath = dateOfDeath;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public LocalDate getClosureDate() {
return closureDate;
}
public void setClosureDate(LocalDate closureDate) {
this.closureDate = closureDate;
}
public LocalDateTime getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDateTime creationDate) {
this.creationDate = creationDate;
}
#OneToMany(orphanRemoval = true, mappedBy = "dependantToTransfer")
public List<DependantTransferRequest> getTransferRequests() {
return transferRequests;
}
public void setTransferRequests(List<DependantTransferRequest> transferRequests) {
this.transferRequests = transferRequests;
}
}
Composite Key:
#Embeddable
public class CompositePolicyMemberPK implements Serializable {
private String policyNumber;
private String suffixNumber;
private static final long serialVersionUID = 1L;
public CompositePolicyMemberPK(String policyNumber, String suffixNumber) {
super();
this.policyNumber = policyNumber;
this.suffixNumber = suffixNumber;
}
public CompositePolicyMemberPK() {
super();
}
#Column(length = 30)
public String getPolicyNumber() {
return this.policyNumber;
}
public void setPolicyNumber(String policyNumber) {
this.policyNumber = policyNumber;
}
#Column(length = 2)
public String getSuffixNumber() {
return this.suffixNumber;
}
public void setSuffixNumber(String suffixNumber) {
this.suffixNumber = suffixNumber;
}
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof CompositePolicyMemberPK)) {
return false;
}
CompositePolicyMemberPK other = (CompositePolicyMemberPK) o;
return (getPolicyNumber() == null ? other.getPolicyNumber() == null : getPolicyNumber().equals(other.getPolicyNumber())) && (getSuffixNumber() == null ? other.getSuffixNumber() == null : getSuffixNumber().equals(other.getSuffixNumber()));
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (getPolicyNumber() == null ? 0 : getPolicyNumber().hashCode());
result = prime * result + (getSuffixNumber() == null ? 0 : getSuffixNumber().hashCode());
return result;
}
#Override
public String toString() {
return this.getPolicyNumber() + "-" + this.getSuffixNumber();
}
}
The code that is responsible for persisiting the policy is as follows:
public Subscriber addMemberToSteward(Long stewardId, Subscriber subscriber) {
Steward steward = this.findStewardById(stewardId);
if(steward == null){
throw new EcosureException(String.format("No steward found with id '%s'.",stewardId));
}
final BillingStatus billingStatus = BillingStatus.REG_IN_PROGRESS;
final MemberStatus memberStatus = MemberStatus.NEW;
final ProductPackage product = productService.findPackageById(subscriber.getProductPackageId());
subscriber.setNationalId(nationalIDNumberUtils.formatIdNumber(subscriber.getNationalId()));
final PolicyHolder policyHolder = convertToPolicyHolder(subscriber, product, billingStatus, memberStatus);
Policy policy = getPolicyFromSubscriberInfo(subscriber, policyHolder);
policy.setSteward(steward);
policy.setStatus(PolicyStatus.NEW);
System.out.println("Policy Holder" + policyHolder);
policyRepository.save(policy);
return subscriber;
}
The getPolicyFromSubscriberInfo method is below:
private Policy getPolicyFromSubscriberInfo(final Subscriber subscriberInfo, final PolicyHolder policyHolder) throws {
final Policy policy = new Policy();
policy.setMsisdn(subscriberInfo.getMsisdn());
policy.setPolicyNumber(policyNumberGenerator.getNextPolicyNumber());
policy.setPolicyName(policyHolder.getFirstname() + " " + policyHolder.getSurname());
policyHolder.setPolicy(policy);
CompositePolicyMemberPK policyMemberId = new CompositePolicyMemberPK();
policyMemberId.setPolicyNumber(policy.getPolicyNumber());
policyMemberId.setSuffixNumber(policyNumberGenerator.getNextSuffix(policy.getPolicyNumber(),true));
policyHolder.setPolicyMemberId(policyMemberId);
policy.setPolicyHolder(policyHolder);
return policy;
}
The PolicyRepository is shown below:
public interface PolicyRepository extends JpaRepository<Policy, String> {
}
When I try to persist a Policy entity I am getting the error below:
2016-12-09 09:47:43,461 ERROR [io.undertow.request] (default task-15) UT005023: Exception handling request to /ecosure-api/api/v3/stewards/243/policies: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist(); nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at com.econetwireless.ecosure.api.filters.AuthenticationTokenFilter.doFilter(AuthenticationTokenFilter.java:60)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:282)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:261)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:80)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:172)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:774)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist(); nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:418)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:492)
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:133)
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:213)
at com.sun.proxy.$Proxy1272.save(Unknown Source)
at com.econetwireless.ecosure.service.stewards.StewardServiceImpl.addMemberToSteward(StewardServiceImpl.java:115)
at com.econetwireless.ecosure.api.controllers.StewardController.addMemberToGroup(StewardController.java:91)
at com.econetwireless.ecosure.api.controllers.StewardController$$FastClassBySpringCGLIB$$69e389b2.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.econetwireless.ecosure.api.controllers.StewardController$$EnhancerBySpringCGLIB$$2d501d51.addMemberToGroup(<generated>)
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:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 65 more
Caused by: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1152)
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:483)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
at com.sun.proxy.$Proxy1267.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:506)
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:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
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)
... 95 more
Caused by: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:80)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:768)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:761)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:80)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:391)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:316)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:155)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:104)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:414)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:252)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:778)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:751)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:756)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146)
Can anyone please assist me in identifying where I am going wrong.

Spring Data missing property error when initialising the SOLR repository

I'm relatively new to spring. I'm trying to set up the spring-data-solr package. I'm using this customer class for both the JPA persistence with hibernate, and for writing to SOLR via the SOLR Data adapter. It hasn't worked yet.
When I start the server I get this error in the log:
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.ideafactory.mvc.customers.model.CustomerRepository com.ideafactory.mvc.customers.admin.AddressController.customerRepository;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed;
nested exception is org.springframework.data.mapping.PropertyReferenceException: No property flush found for type Customer!
Originally, it was saying no property "save" found on customer, so I did a test and just added a property called save. Then if I add flush, it says no property "delete" found. But it doesn't seem right to just keep adding these properties onto my domain class. I seem to be missing something on this Customer class to support the SOLR repository (maybe).
Also if I disable the #EnableSOLRRepositories annotation on my configuration class, the error doesn't happen, so it's definitely a problem related to the SOLR repository configuration.
Does anyone have any idea what the problem might be?
The class is below:
package com.ideafactory.mvc.customers.model;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
#Entity(name = "customer")
#Table(name = "customers")
public class Customer implements UserDetails {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Basic
#Column(nullable = false)
private String preferredName;
#Basic
#Column(nullable = false)
private String firstName;
#Basic
#NotEmpty
private String lastName;
#Basic
#Column(unique = true)
#NotEmpty
#Email
private String email;
#Basic
#Column(nullable = false)
private String password;
#Basic
#Column(nullable = true)
private Date dateOfBirth;
#Basic
#Column(nullable = true)
private String bio;
#Basic
#Column(nullable = true)
private String website;
#Basic
#Column(nullable = true)
private Date lastLogin;
#Basic
#Column(nullable = true)
private Date lastLogout;
#Enumerated(EnumType.STRING)
private CustomerStatus status;
#Basic
#Column(nullable = false)
private Date createdAt;
#Basic
#Column(nullable = false)
private Date lastModified;
#Type(type = "org.hibernate.type.NumericBooleanType")
private boolean requiresReset;
#Type(type="org.hibernate.type.NumericBooleanType")
private boolean subscriber;
#Enumerated(EnumType.STRING)
private Gender gender;
#Basic
private String phoneNumber;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "customer")
private List<Address> addressBook;
public String getPreferredName() {
return preferredName;
}
public void setPreferredName(String preferredName) {
this.preferredName = preferredName;
}
public boolean isSubscriber() {
return subscriber;
}
public void setSubscriber(boolean subscriber) {
this.subscriber = subscriber;
}
public boolean isRequiresReset() {
return requiresReset;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public boolean getRequiresReset() {
return requiresReset;
}
public void setRequiresReset(boolean requiresReset) {
this.requiresReset = requiresReset;
}
#ManyToMany
#JoinTable(
name="customer_roles",
joinColumns={#JoinColumn(name="customerId", referencedColumnName="id")},
inverseJoinColumns={#JoinColumn(name="roleId", referencedColumnName="id")})
private List<Role> roles;
#Transient
public boolean isPersisted() {
return (this.id != null);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String name) {
this.firstName = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password)
{
this.password = password;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
List<Role> userRoles = this.getRoles();
if(userRoles != null)
{
for (Role role : userRoles) {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
authorities.add(authority);
}
}
return authorities;
}
#Override
public String getUsername()
{
return getEmail();
}
#Override
public String getPassword()
{
return this.password;
}
#Override
public boolean isAccountNonExpired()
{
return true;
}
#Override
public boolean isAccountNonLocked()
{
return true;
}
#Override
public boolean isCredentialsNonExpired()
{
return true;
}
#Override
public boolean isEnabled()
{
return true;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
#PrePersist
void createdAt() {
this.createdAt = this.lastModified = new Date();
}
#PreUpdate
void updatedAt() {
this.createdAt = new Date();
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public Date getLastLogout() {
return lastLogout;
}
public void setLastLogout(Date lastLogout) {
this.lastLogout = lastLogout;
}
public CustomerStatus getStatus() {
return status;
}
public void setStatus(CustomerStatus status) {
this.status = status;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public List<Address> getAddressBook() {
return addressBook;
}
public void setAddressBook(List<Address> addressBook) {
this.addressBook = addressBook;
}
}
This was all I had for the eCustomer Repository. Am I supposed to implement an extension class?
package com.ideafactory.mvc.customers.model;
import org.springframework.data.solr.repository.SolrCrudRepository;
/**
* This is the SOLR repository handler
*/
public interface CustomerSolrCrudRepositoryImpl extends SolrCrudRepository<Customer, String> {
}
************ Update Below ***************
I've narrowed the problem down a little. I downloaded the source code for the spring jpa and stuck a debug point on the SolrRepositoryFactory class. So this is bizarre, but it's trying to resolve the named queries from my hibernate JPA repository using SOLR. So at the point the exception happens, it's trying to initialise what looks like a named query against SOLR. In my CustomerRepository (the Hibernate one) I've got findByEmail(String email).
What am I missing here? Why would the Solr repository initialisation be doing anything with my Hibernate customer repository definition?
/**
* Created on 30/06/2014.
*/
public interface CustomerRepository extends JpaRepository<Customer, Long> {
public List<Customer> findByEmail(String emailAddress);
public Address findOneByAddressBookId(Long addressId);
}
SOLR Config:
/**
* This class initialises the SOLR repositories.
*/
#Configuration
#EnableSolrRepositories(value = "com.ideafactory", multicoreSupport = true)
public class SolrConfig {
private static final String PROPERTY_NAME_SOLR_SERVER_URL = "solr.server.url";
#Resource
private Environment environment;
#Bean
public SolrServerFactory solrServerFactory() {
return new MulticoreSolrServerFactory(new HttpSolrServer(
environment.getRequiredProperty(PROPERTY_NAME_SOLR_SERVER_URL)));
}
#Bean
public SolrOperations solrTemplate1() {
SolrTemplate solrTemplate = new SolrTemplate(solrServerFactory());
solrTemplate.setSolrCore("core1");
return solrTemplate;
}
#Bean
public SolrOperations solrTemplate2() {
SolrTemplate solrTemplate = new SolrTemplate(solrServerFactory());
solrTemplate.setSolrCore("core2");
return solrTemplate;
}
#Bean
public SolrServer solrServer() throws MalformedURLException, IllegalStateException {
return new HttpSolrServer(environment.getRequiredProperty(PROPERTY_NAME_SOLR_SERVER_URL));
}
}
The stack trace follows.
17:34:39.966 ERROR org.springframework.web.context.ContextLoader 318 initWebApplicationContext - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ideafactory.mvc.customers.model.CustomerRepository com.ideafactory.mvc.customers.admin.AddressController.customerRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) ~[AbstractBeanFactory$1.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[DefaultSingletonBeanRegistry.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) ~[AbstractApplicationContext.class:4.0.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) ~[AbstractApplicationContext.class:4.0.0.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:381) ~[ContextLoader.class:4.0.0.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293) [ContextLoader.class:4.0.0.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) [ContextLoaderListener.class:4.0.0.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4758) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5184) [catalina.jar:8.0.9]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.0.9]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724) [catalina.jar:8.0.9]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714) [catalina.jar:8.0.9]
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1588) [catalina.jar:8.0.9]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300) [tomcat-coyote.jar:8.0.9]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) [?:1.7.0_45]
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) [?:1.7.0_45]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463) [catalina.jar:8.0.9]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413) [catalina.jar:8.0.9]
28-Jul-2014 17:34:39.975 SEVERE [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Error listenerStart
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
28-Jul-2014 17:34:39.976 SEVERE [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300) [tomcat-coyote.jar:8.0.9]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) [?:1.7.0_45]
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1420) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848) [?:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322) [?:1.7.0_45]
at sun.rmi.transport.Transport$1.run(Transport.java:177) [?:1.7.0_45]
at sun.rmi.transport.Transport$1.run(Transport.java:174) [?:1.7.0_45]
at java.security.AccessController.doPrivileged(Native Method) [?:1.7.0_45]
at sun.rmi.transport.Transport.serviceCall(Transport.java:173) [?:1.7.0_45]
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:556) [?:1.7.0_45]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:811) [?:1.7.0_45]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:670) [?:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [?:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [?:1.7.0_45]
at java.lang.Thread.run(Thread.java:744) [?:1.7.0_45]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ideafactory.mvc.customers.model.CustomerRepository com.ideafactory.mvc.customers.admin.AddressController.customerRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) ~[AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[InjectionMetadata.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
... 56 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) ~[AbstractBeanFactory$1.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[DefaultSingletonBeanRegistry.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1014) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ~[AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[InjectionMetadata.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
... 56 more
28-Jul-2014 17:34:39.980 WARNING [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.loader.WebappClassLoader.clearReferencesJdbc The web application [] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241) ~[PropertyPath.class:?]
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76) ~[Part.class:?]
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213) ~[PartTree$OrPart.class:?]
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321) ~[PartTree$Predicate.class:?]
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301) ~[PartTree$Predicate.class:?]
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82) ~[PartTree.class:?]
at org.springframework.data.solr.repository.query.PartTreeSolrQuery.<init>(PartTreeSolrQuery.java:36) ~[PartTreeSolrQuery.class:?]
at org.springframework.data.solr.repository.support.SolrRepositoryFactory$SolrQueryLookupStrategy.resolveQuery(SolrRepositoryFactory.java:130) ~[SolrRepositoryFactory$SolrQueryLookupStrategy.class:?]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320) ~[RepositoryFactorySupport$QueryExecutorMethodInterceptor.class:?]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169) ~[RepositoryFactorySupport.class:?]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224) ~[RepositoryFactoryBeanSupport.class:?]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210) ~[RepositoryFactoryBeanSupport.class:?]
at org.springframework.data.solr.repository.support.SolrRepositoryFactoryBean.afterPropertiesSet(SolrRepositoryFactoryBean.java:66) ~[SolrRepositoryFactoryBean.class:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) ~[AbstractBeanFactory$1.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[DefaultSingletonBeanRegistry.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1014) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ~[AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[InjectionMetadata.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
... 56 more
Ok for reference in case anyone needs it. I don't think I've quite fixed it, or understand why it was happening. But I've worked around this by separating the JPA repositories and SOLR repositories into separate packages, and in the annotation for each explicitly setting the full package directory.
I guess it could just be me not understanding how the repository initialisers work in Spring. So I just changed it to these values and it seems to have at least resolved the first issue:
e.g
#EnableJpaRepositories(basePackages="com.ideafactory.mvc.repositories.jpa")
#EnableSolrRepositories(value = "com.ideafactory.mvc.repositories.solr", multicoreSupport = true)

Resources