Facing InvalidDataAccessResourceUsageException: could not extract ResultSet - java
While creating new user i am getting error as below.
I am using Spring-data-jpa and have created UserRepository for that also.
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
UserDesc.java
#Entity
#Table(name = "USER_DESC")
public class UserDesc implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 758374824732125303L;
private String userId;
private String password;
private String emailId;
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
public UserDesc() {
}
public UserDesc(String userId, String password, String firstName, String updtUserid, Date timeStamp,
String lastAction) {
this.userId = userId;
this.password = password;
this.firstName = firstName;
this.updtUserid = updtUserid;
this.timeStamp = timeStamp;
this.lastAction = lastAction;
}
public UserDesc(String userId, String password, String emailId, Set<UserRole> userRoles) {
this.userId = userId;
this.password = password;
this.emailId = emailId;
this.userRoles = userRoles;
}
public UserDesc(String userId, String emailId, String password) {
this.userId = userId;
this.emailId = emailId;
this.password = password;
}
#Id
#Column(name = "USER_ID", unique = true, nullable = false, length = 50)
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name = "PASSWORD", nullable = false, length = 250)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "EMAIL_ID", length = 100)
public String getEmailId() {
return this.emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER, mappedBy = "userDesc")
public Set<UserRole> getUserRoles() {
return this.userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
UserRole.java
#Entity
#Table(name = "IVMT_USER_ROLE")
public class UserRole implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -7237890967514573717L;
#Id
private UserRoleId id;
private RoleDesc roleDesc;
private UserDesc userDesc;
public UserRole() {
}
public UserRole(UserRoleId id, RoleDesc roleDesc, UserDesc userDesc ) {
this.id = id;
this.roleDesc = roleDesc;
this.userDesc = userDesc;
}
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "userId", column = #Column(name = "USER_ID", nullable = false, length = 50)),
#AttributeOverride(name = "roleName", column = #Column(name = "ROLE_NAME", nullable = false, length = 50)) })
public UserRoleId getId() {
return this.id;
}
public void setId(UserRoleId id) {
this.id = id;
}
#JsonBackReference
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ROLE_NAME", nullable = false, insertable = false, updatable = false)
public RoleDesc getRoleDesc() {
return this.roleDesc;
}
public void setRoleDesc(RoleDesc roleDesc) {
this.roleDesc = roleDesc;
}
#JsonBackReference
#ManyToOne(fetch = FetchType.LAZY)
#JoinTable(name = "IVMT_USER_DESC")
public UserDesc getUserDesc() {
return this.userDesc;
}
public void setUserDesc(UserDesc userDesc) {
this.userDesc = userDesc;
}
}
UserRoleId.java
#Embeddable
public class UserRoleId implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 3699646506024636048L;
private String userId;
private String roleName;
public UserRoleId() {
}
public UserRoleId(String userId, String roleName) {
this.userId = userId;
this.roleName = roleName;
}
#Column(name = "USER_ID", nullable = false, length = 50)
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name = "ROLE_NAME", nullable = false, length = 50)
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
RoleDesc.java
#Entity
#Table(name = "IVMT_ROLE_DESC")
public class RoleDesc implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -3095436060121680832L;
private String roleName;
private String roleDesc;
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
public RoleDesc() {
}
public RoleDesc(String roleName) {
this.roleName = roleName;
}
public RoleDesc(String roleName, String roleDesc,
Set<UserRole> userRoles) {
this.roleName = roleName;
this.roleDesc = roleDesc;
this.userRoles = userRoles;
}
#Id
#Column(name = "ROLE_NAME", unique = true, nullable = false, length = 50)
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#Column(name = "ROLE_DESC")
public String getRoleDesc() {
return this.roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
#JsonBackReference
#OneToMany(fetch = FetchType.LAZY, mappedBy = "roleDesc")
public Set<UserRole> getUserRoles() {
return this.userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
Creating new User code as below.
userDesc = new UserDesc(userId, emailId, password);
Set<UserRole> userRoles = new HashSet<>();
RoleDesc roleDesc = roleRepository.findByRoleName("USER")
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
UserRoleId id = new UserRoleId(signUpRequest.getUserId(), roleDesc.getRoleName());
UserRole userRole = new UserRole(id, roleDesc, userDesc);
userRoles.add(userRole);
userDesc.setUserRoles(userRoles);
userRepository.saveAndFlush(userDesc);
Error Full Stack:
Hibernate: select TOP(?) userdesc0_.user_id as col_0_0_ from ivmt_user_desc userdesc0_ where userdesc0_.user_id=?
Hibernate: select TOP(?) userdesc0_.user_id as col_0_0_ from ivmt_user_desc userdesc0_ where userdesc0_.email_id=?
Hibernate: select roledesc0_.role_name as role_nam1_9_, roledesc0_.last_action as last_act2_9_, roledesc0_.role_desc as role_des3_9_, roledesc0_.time_stamp as time_sta4_9_, roledesc0_.updt_userid as updt_use5_9_ from ivmt_role_desc roledesc0_ where roledesc0_.role_name=?
Hibernate: select userdesc0_.user_id as user_id1_11_0_, userdesc0_.cf_user_date1 as cf_user_2_11_0_, userdesc0_.cf_user_date2 as cf_user_3_11_0_, userdesc0_.cf_user_date3 as cf_user_4_11_0_, userdesc0_.cf_user_date4 as cf_user_5_11_0_, userdesc0_.cf_user_date5 as cf_user_6_11_0_, userdesc0_.cf_user_flag1 as cf_user_7_11_0_, userdesc0_.cf_user_flag2 as cf_user_8_11_0_, userdesc0_.cf_user_flag3 as cf_user_9_11_0_, userdesc0_.cf_user_flag4 as cf_user10_11_0_, userdesc0_.cf_user_flag5 as cf_user11_11_0_, userdesc0_.cf_user_num1 as cf_user12_11_0_, userdesc0_.cf_user_num2 as cf_user13_11_0_, userdesc0_.cf_user_num3 as cf_user14_11_0_, userdesc0_.cf_user_num4 as cf_user15_11_0_, userdesc0_.cf_user_num5 as cf_user16_11_0_, userdesc0_.cf_user_vch1 as cf_user17_11_0_, userdesc0_.cf_user_vch2 as cf_user18_11_0_, userdesc0_.cf_user_vch3 as cf_user19_11_0_, userdesc0_.cf_user_vch4 as cf_user20_11_0_, userdesc0_.cf_user_vch40001 as cf_user21_11_0_, userdesc0_.cf_user_vch40002 as cf_user22_11_0_, userdesc0_.cf_user_vch5 as cf_user23_11_0_, userdesc0_.contact_no as contact24_11_0_, userdesc0_.email_id as email_i25_11_0_, userdesc0_.first_name as first_n26_11_0_, userdesc0_.last_action as last_ac27_11_0_, userdesc0_.last_name as last_na28_11_0_, userdesc0_.middle_name as middle_29_11_0_, userdesc0_.password as passwor30_11_0_, userdesc0_.time_stamp as time_st31_11_0_, userdesc0_.updt_userid as updt_us32_11_0_ from ivmt_user_desc userdesc0_ where userdesc0_.user_id=?
Hibernate: select userrole0_.role_name as role_nam1_12_0_, userrole0_.user_id as user_id2_12_0_, userrole0_.last_action as last_act3_12_0_, userrole0_.role_desc as role_des4_12_0_, userrole0_.time_stamp as time_sta5_12_0_, userrole0_.updt_userid as updt_use6_12_0_, userrole0_.user_desc as user_des7_12_0_ from ivmt_user_role userrole0_ where userrole0_.role_name=? and userrole0_.user_id=?
2020-05-13 15:26:16.857 WARN 8840 --- [onPool-worker-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 207, SQLState: S0001
2020-05-13 15:26:16.857 ERROR 8840 --- [onPool-worker-3] o.h.engine.jdbc.spi.SqlExceptionHelper : Invalid column name 'role_desc'.
2020-05-13 15:26:16.859 INFO 8840 --- [onPool-worker-3] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:390) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:163) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:104) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:197) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4379) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:569) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:537) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:208) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:332) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:108) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:74) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:118) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.fireLoadNoChecks(SessionImpl.java:1168) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1033) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:687) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:464) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.ManyToOneType.resolve(ManyToOneType.java:240) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:457) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.EntityType.replace(EntityType.java:358) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.CollectionType.replaceElements(CollectionType.java:587) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.CollectionType.replace(CollectionType.java:750) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.AbstractType.replace(AbstractType.java:164) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.type.TypeHelper.replaceAssociations(TypeHelper.java:254) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:477) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:248) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:318) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:172) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:70) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:775) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:762) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy177.merge(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:557) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.saveAndFlush(SimpleJpaRepository.java:569) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:371) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:204) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:657) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:621) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy179.saveAndFlush(Unknown Source) ~[na:na]
at com.kap.IM.service.impl.UserServiceImpl.createUser(UserServiceImpl.java:99) ~[classes/:na]
at com.kap.IM.controllers.UserController.lambda$4(UserController.java:79) ~[classes/:na]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1582) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[na:1.8.0_92]
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'role_desc'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1624) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:594) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:524) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7194) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2979) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:248) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:223) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:446) ~[mssql-jdbc-7.4.1.jre8.jar:na]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.2.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
... 71 common frames omitted
2020-05-13 15:26:16.865 ERROR 8840 --- [nio-7070-exec-2] c.k.I.a.exception.IvmtExceptionHandler : null
com.kap.IM.api.exception.IvmtException: Unable to create new user
at com.kap.IM.api.IvmtBaseRestController.buildErrorResponse(IvmtBaseRestController.java:27) ~[classes/:na]
at com.kap.IM.controllers.UserController.lambda$5(UserController.java:87) ~[classes/:na]
at java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:760) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:736) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1595) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1582) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[na:1.8.0_92]
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[na:1.8.0_92]
Caused by: java.util.concurrent.CompletionException: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:273) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:280) ~[na:1.8.0_92]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1592) ~[na:1.8.0_92]
... 5 common frames omitted
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy179.saveAndFlush(Unknown Source) ~[na:na]
at com.kap.IM.service.impl.UserServiceImpl.createUser(UserServiceImpl.java:99) ~[classes/:na]
at com.kap.IM.controllers.UserController.lambda$4(UserController.java:79) ~[classes/:na]
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) ~[na:1.8.0_92]
... 5 common frames omitted
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:390)
2020-05-13 15:26:16.868 WARN 8840 --- [nio-7070-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [com.kap.IM.api.exception.IvmtException: Unable to create new user]
Let me know where I am making mistake in setting proper joins between tables.
Related
could not delete collection rows: The column index is out of range
I have following Hibernate classes: 'Skill' has many 'SkillTranslation' which extends 'ResourceTranslation' Skill: #Entity #Table(name = "skill") #ToString #Getter #Setter public class Skill { #Id private String id; #OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) #JoinColumn(name = "key", referencedColumnName = "id") private Set<SkillTranslation> localizedDescription; } SkillTranslation: #Entity #Table(name = "skill_translation") public class SkillTranslation extends ResourceTranslation{ } ResourceTranslation: #ToString #Getter #Setter #MappedSuperclass #IdClass(ResourceTranslation.PK.class) public class ResourceTranslation implements Serializable { #Id private String key; #Id #Enumerated(EnumType.STRING) private Locale locale; #Column(length = 10000) private String value; #Data #AllArgsConstructor #NoArgsConstructor public static class PK implements Serializable { private String key; #Enumerated(EnumType.STRING) private Locale locale; } } The problem occurs when I try to update an existing skill(initial version has 3 localized description and new one has only 2) Stacktrace: org.springframework.dao.DataIntegrityViolationException: could not delete collection rows: [hidden.Skill.localizedDescription#71f13be5-c692-46d3-875c-62d0905bb5ba]; SQL [update skill_translation set key=null where key=? and locale=?]; nested exception is org.hibernate.exception.DataException: could not delete collection rows: [hidden.Skill.localizedDescription#71f13be5-c692-46d3-875c-62d0905bb5ba] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:302) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:538) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:633) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:386) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) at hidden.ImportSkillsService$$EnhancerBySpringCGLIB$$2d832c5f.importSkills(<generated>) at hidden.syncAll(hidden.java:21) at hidden.job.RefreshAllJob.refresh(RefreshAllJob.java:22) at hidden.BaseRefreshJob.run(BaseRefreshJob.java:33) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: org.hibernate.exception.DataException: could not delete collection rows: [hidden.Skill.localizedDescription#71f13be5-c692-46d3-875c-62d0905bb5ba] at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) at org.hibernate.persister.collection.AbstractCollectionPersister.deleteRows(AbstractCollectionPersister.java:1509) at org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:87) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1363) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:454) at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3213) at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2381) at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534) ... 17 common frames omitted Caused by: org.postgresql.util.PSQLException: The column index is out of range: 3, number of columns: 2. at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65) at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128) at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:1019) at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:343) at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:330) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setString(HikariProxyPreparedStatement.java) at org.hibernate.type.descriptor.sql.VarcharTypeDescriptor$1.doBind(VarcharTypeDescriptor.java:46) at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:73) at org.hibernate.metamodel.model.convert.internal.NamedEnumValueConverter.writeValue(NamedEnumValueConverter.java:75) at org.hibernate.type.EnumType.nullSafeSet(EnumType.java:262) at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:170) at org.hibernate.type.ComponentType.nullSafeSet(ComponentType.java:365) at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:280) at org.hibernate.persister.collection.AbstractCollectionPersister.writeElementToWhere(AbstractCollectionPersister.java:959) at org.hibernate.persister.collection.AbstractCollectionPersister.deleteRows(AbstractCollectionPersister.java:1473) ... 35 common frames omitted Hibernate version: 5.4.20.Final
Spring + Mongodb with a Null id Issue
I'm working on a academic project with Spring + MongoDB I have three Document User.java #Document public class User implements UserDetails, Serializable { private static final long SerialVersionUID = 147147L; #Id private String id; private String username; private String password; private String firstname; private String lastname; private String email; private String phone; private boolean enable = true; private Set<UserRole> userRoles = new HashSet<>(); ... } Role.java #Document public class Role implements Serializable { private static final long SerialVersionUID = 456456L; #Id private String id; private String name; ... } UserRole.java #Document(collection = "user_roles") public class UserRole implements Serializable { private static final long SerialVersionUID = 789789L; #Id private String id; #DBRef private User user; #DBRef private Role role; private String name; ... } And a UserServiceImpl.java #Service public class UserServiceImpl implements UserService { private static final Logger LOG = LoggerFactory.getLogger(UserService.class); #Autowired UserRepository userRepository; #Autowired RoleRepository roleRepository; #Autowired UserRoleRepository userRoleRepository; #Override public User createUser(User user, Set<UserRole> userRoles) { User localUser = userRepository.findByUsername(user.getUsername()); if(localUser != null) { LOG.info("User with username {} already exist. Nothing will be done. ", user.getUsername()); } else { for (UserRole ur : userRoles) { roleRepository.save(ur.getRole()); //here is the problem: the userrole instance created cannot generate Id userRoleRepository.save(ur); } user.getUserRoles().addAll(userRoles); localUser = userRepository.save(user); } return localUser; } } and the DemoApplication.java #SpringBootApplication public class DemoApplication implements CommandLineRunner { #Autowired UserService userService; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } #Override public void run(String... args) throws Exception { User user1 = new User(); user1.setFirstname("John"); user1.setLastname("Adams"); user1.setUsername("j"); user1.setPassword(SecurityUtility.passwordEncoder().encode("p")); user1.setEmail("JAdams#gmail.com"); Set<UserRole> userRoles = new HashSet<>(); Role role1 = new Role(); role1.setName("ROLE_USER"); UserRole userRole1 = new UserRole(); userRole1.setRole(role1); userRole1.setUser(user1); userRoles.add(userRole1); userService.createUser(user1, userRoles); } and the ExceptionStackTrack java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:821) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:802) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:341) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE] at com.example.demo.DemoApplication.main(DemoApplication.java:22) [classes/:na] Caused by: org.springframework.data.mapping.MappingException: Cannot create a reference to an object with a NULL id. at org.springframework.data.mongodb.core.convert.MappingMongoConverter.createDBRef(MappingMongoConverter.java:936) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writePropertyInternal(MappingMongoConverter.java:554) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeAssociation(MappingMongoConverter.java:517) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeProperties(MappingMongoConverter.java:494) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:481) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:455) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:399) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:78) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.MongoTemplate.toDocument(MongoTemplate.java:1071) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1254) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:1202) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:82) ~[spring-data-mongodb-2.0.10.RELEASE.jar:2.0.10.RELEASE] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na] at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:377) ~[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:641) ~[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:590) ~[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at com.sun.proxy.$Proxy73.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:564) ~[na:na] at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at com.sun.proxy.$Proxy73.save(Unknown Source) ~[na:na] at com.example.demo.Service.Impl.UserServiceImpl.createUser(UserServiceImpl.java:42) ~[classes/:na] at com.example.demo.DemoApplication.run(DemoApplication.java:46) [classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:818) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE] ... 5 common frames omitted Here I dont't know why roles and users instance can generate automatically but userrole cannot. The console return me an exception that the Id is NULL and cannot be reference. I'm new for this, and I hope someone could give me an answer. thanks.
It seems that you are calling userRoleRepository.save(ur) in case when the User with the provided username does not exist in the database and before actually storing this User in it. I believe you should reorganise your code in a way to store the User first and then store the UserRole with this User set. In other words (code?), in your UserServiceImpl you could try doing something like this: #Override public User createUser(User user, Set<UserRole> userRoles) { User localUser = userRepository.findByUsername(user.getUsername()); if(localUser != null) { LOG.info("User with username {} already exist. Nothing will be done. ", user.getUsername()); } else { user.getUserRoles().addAll(userRoles); localUser = userRepository.save(user); for (UserRole ur : userRoles) { roleRepository.save(ur.getRole()); userRoleRepository.save(ur); } } return localUser; } As you can see, I have only reordered the calls - User is stored first, then go the userRoles for this User.
Springboot mvc java application cannot run when it's set to UPDATE
My web application was working until I decided to put in comments. I messed it up a lot so I changed spring.jpa.hibernate.ddl-auto from upate to create-drop But now, when I spring.jpa.hibernate.ddl-auto = create-drop the application starts and when I change it to spring.jpa.hibernate.ddl-auto = update I get this error: 2017-11-27 15:27:02.481 ERROR 3552 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] at blog.BlogApplication.main(BlogApplication.java:14) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.8.RELEASE.jar:1.5.8.RELEASE] Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] ... 21 common frames omitted Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table comments add constraint FK99rehd3fcds7jsy5dpa39fitm foreign key (comments) references users (id)] at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:386) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:214) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] ... 27 common frames omitted Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: BLOB/TEXT column 'comments' used in key specification without a key length at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_111] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_111] at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_111] at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2483) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607) ~[mysql-connector-java-5.1.44.jar:5.1.44] at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480) ~[mysql-connector-java-5.1.44.jar:5.1.44] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111] at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) ~[tomcat-jdbc-8.5.23.jar:na] at com.sun.proxy.$Proxy88.executeUpdate(Unknown Source) ~[na:na] at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] ... 37 common frames omitted Probably some of my relations are messed up, but I have an ArticleBindingModel public class ArticleBindingModel { private String comments; #NotNull private String title; #NotNull private String content; //--------------------------GETTERS/SETTERS--------------------------- public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } } Article Entity #Entity #Table(name = "articles") public class Article { private Integer id; private String title; private String content; private User author; private User commenter; private Set<Comment> comments; //-----------------------------CONSTRUCTORS-------------------------- public Article(String title, String content, User author) { this.title = title; this.content = content; this.author = author; this.comments = new HashSet<>(); } public Article(){} //-------------------------GETTERS/SETTERS---------------------------- #Id #GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } #Column(nullable = false) public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } #Column(columnDefinition = "text", nullable = false) public String getContent() { return content; } public void setContent(String content) { this.content = content; } #ManyToOne() #JoinColumn(nullable = false, name = "authorId") public User getAuthor() { return author; } public void setAuthor(User author) { this.author = author; } #OneToMany(mappedBy = "article") public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; } } Comment Entity #Entity #Table(name = "comments") public class Comment { private Integer id; private User commenter; private String comments; private Article article; //-----------------------------CONSTRUCTORS---------------------- public Comment(User commenter, String comments, Article article) { this.commenter = commenter; this.comments = comments; this.article = article; } public Comment(){} //----------------------METHODS----------------------------------- //--------------------GETTERS/SETTERS----------------------------- #Id #GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } #Column(nullable = false, columnDefinition = "LONGBLOB") public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } #ManyToOne() #JoinColumn(nullable = false, name = "commenterId") public User getCommenter() { return commenter; } public void setCommenter(User commenter) { this.commenter = commenter; } #ManyToOne() #JoinColumn(nullable = false, name = "articleId") public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } } User Entity #Entity #Table(name = "users") public class User { private Integer id; private String username; private Set<Article> articles; private Set<Comment> comments; //-----------------------------------CONSTRUCTORS----------------------------------- public User (String username) { this.username = username; this.articles = new HashSet<>(); this.comments = new HashSet<>(); } public User() { } //------------------------------------METHODS------------------------------------------ //----------------------------------GETTERS/SETTERS-------------------------------------- #Id #GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } #Column(name = "username", length = 80, nullable = false, unique = true) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } #OneToMany(mappedBy = "author") public Set<Article> getArticles() { return articles; } public void setArticles(Set<Article> articles) { this.articles = articles; } #OneToMany(mappedBy = "comments") public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; } } And then I have a repository for the appropriate Entities. I have heavily edited the code so I won't be a "heresallmycode" guy. But, I'm pretty sure that my annotation relations are the problem. I wanted there to be comments that have a MANY TO ONE relationship with an article, a user that would appear above the comments when they are posted and a reverse ONE TO MANY relationship of the article with the comments. When the tables are created using the create paramater, my articles table was not emptied(I had it on update before), I had to manually drop it. Now, when the table is created it's empty. I thought that was worth mentioning. I can post the create logs If that would be neccessary. EDIT I forgot my ArticleController #Controller public class ArticleController { #Autowired private ArticleRepository articleRepository; #Autowired private UserRepository userRepository; #Autowired private CommentRepository commentRepository; //---------------------------------METHODS----------------------- //ARTICLE DETAILS-------------------------------------------------- #GetMapping("/article/{id}") public String details(Model model, #PathVariable Integer id) { if (!this.articleRepository.exists(id)) { return "redirect:/"; } UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();//This was inside the IF if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) { User entityUser = this.userRepository.findByEmail(principal.getUsername()); model.addAttribute("user", entityUser); } //Getting the article Article article = this.articleRepository.findOne(id); //Comments Set<Comment> comments = this.commentRepository.findCommentsByArticleId(id);//findAllByArticlesId //Set<User> commenters = this.userRepository.findAllByComments(comments); //Models model.addAttribute("article", article); //model.addAttribute("commenters", commenters); model.addAttribute("comments", comments); model.addAttribute("view", "article/details"); return "base-layout"; } #PostMapping("/article/{id}") #PreAuthorize("isAuthenticated()") public String detailsProcess(#PathVariable Integer id, ArticleBindingModel articleBindingModel) { if (!this.articleRepository.exists(id)) { return "redirect:/"; } //Getting the article Article article = this.articleRepository.findOne(id); //Getting the commenter UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User commenter = this.userRepository.findByEmail(principal.getUsername()); //Setting the values for the comment section return "redirect:/article/{id}"; } }
You have defined the relation to User in Comment as: #ManyToOne() #JoinColumn(nullable = false, name = "commenterId") public User getCommenter() { return commenter; } but you are referring to comments string column on the Comment side of the relationship. You should change the mappedBy to: #OneToMany(mappedBy = "commenter") public Set<Comment> getComments() { return comments; }
Unknown column error using hibernate OneToMany mapping
I m new to hibernate and having error Unknown column in OneToMany mapping. I m trying to implement the one to many relationships using hibernate but having an error. Here is my Code: Department Class: #Entity #Table(name="department") public class Department { #Id #Column(name="dept_id") private int id; #Column(name="dept_name") private String name; #OneToMany(mappedBy="department", cascade=CascadeType.ALL, fetch=FetchType.EAGER) private Collection<Employee> employees = new ArrayList<Employee>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<Employee> getEmployees() { return employees; } public void setEmployees(Collection<Employee> employees) { this.employees = employees; } } Employee Class: #Entity #Table(name = "employee") public class Employee { #Column(name="emp_id") #Id private int id; #Column(name="emp_name") private String name; #ManyToOne private Department department; public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Employee Dao Class: public class EmployeeDao { public void addEmployee(Employee emp, int id){ Department department = new Department(); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); department = (Department) session.get(Department.class, id); emp.setDepartment(department); department.getEmployees().add(emp); session.save(emp); session.getTransaction().commit(); session.close(); sessionFactory.close(); } } Here is my Database : CREATE TABLE `department` ( `dept_id` int(11) NOT NULL, `dept_name` varchar(255) DEFAULT NULL ) CREATE TABLE `employee` ( `emp_id` int(11) NOT NULL, `emp_name` varchar(255) DEFAULT NULL, `dept_id` int(11) DEFAULT NULL ) Stack Trace : WARNING: #{employee.addEmployee}: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0] javax.faces.FacesException: #{employee.addEmployee}: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0] at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) at javax.faces.component.UICommand.broadcast(UICommand.java:315) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:722) Caused by: javax.faces.el.EvaluationException: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0] at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) ... 27 more Caused by: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.loader.Loader.loadEntity(Loader.java:2041) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76) at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3293) at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496) at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477) at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227) at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998) at com.hibCollection.dao.EmployeeDao.addEmployee(EmployeeDao.java:21) at com.hibCollection.mangedBean.EmployeeManageBean.addEmployee(EmployeeManageBean.java:29) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.el.parser.AstValue.invoke(AstValue.java:278) at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273) at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) ... 28 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'employees1_.department_dept_id' in 'field list' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1031) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2543) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1737) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1888) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1953) at org.hibernate.loader.Loader.doQuery(Loader.java:802) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274) at org.hibernate.loader.Loader.loadEntity(Loader.java:2037) ... 49 more Can you please tell me what I'm doing wrong here? :)
Try make so #ManyToOne #JoinColumn(name = "dept_id") private Department department;
The default column name for mapping is of type, table_name + '_' + target_table_primary_key. This is why it is looking for department_dept_id You can specify mapping column using annotations. #JoinColumn(name="dept_id").
Property-based access is the right way for using #OneToMany and #ManyToOne annotation Use #OneToMany like below: private Collection<Employee> employees; #OneToMany(mappedBy="department", cascade=CascadeType.ALL, fetch=FetchType.EAGER) public Collection<Employee> getEmployees() { return employees; } public void setEmployees(Collection<Employee> employees) { this.employees = employees; } And use #ManyToOne like below: private Department department; #ManyToOne #JoinColumn(name = "dept_id") public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } Also you need to use an empty constructor in your model classes, as hibernate wants it. If you use #OnetoMany and #ManyToOne with File-based access then you will get the following error Initial SessionFactory creation failed.org.hibernate.MappingException: Could not determine type for: java.util.List, for columns: [org.hibernate.mapping.Column(relatedResources)]
Give SQL exception when try to auto generate the id
I can insert data without generate the id,But when it is generated it is not working My Entity class #Entity public class User { long id; String name; #Id #GeneratedValue(strategy=GenerationType.IDENTITY) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Code where I try to insert data #Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public void addUser(){ User user=new User(); user.setName("Sanja ela"); userDao.save(user); System.out.println("elane"); } And the Exception javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1316) at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:881) 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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241) at com.sun.proxy.$Proxy12.persist(Unknown Source) at com.sanja.test.myDao.impl.UserDaoImpl.save(UserDaoImpl.java:20) at com.sanja.test.myService.App.addUser(App.java:36) at com.sanja.test.myService.App$$FastClassByCGLIB$$3c8037a4.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) at com.sanja.test.myService.App$$EnhancerByCGLIB$$cd9d01ed.addUser(<generated>) at com.sanja.test.myService.App.main(App.java:27) Caused by: org.hibernate.exception.GenericJDBCException: could not execute statement at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2966) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3477) at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81) at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362) at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203) at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183) at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167) at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321) at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286) at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192) at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125) at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:78) at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208) at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151) at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78) at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:852) at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:826) at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:830) at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:875) ... 19 more Caused by: java.sql.SQLException: Field 'id' doesn't have a default value at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133) ... 40 more
You can change id column to be "auto_increment" not null in the database and it should work.
I found an answer myself although Alex provided a valid answer. We have to define the column name of the primary key as ID so that hibernate create the default value of that field as auto increment by it self. If we do not name it as ID it will put no default value. Then as Alex said we have to set it manually. #Id #Column(name = "ID") #GeneratedValue(strategy=GenerationType.AUTO) long id; When we define #Column(name = "ID") hibernate will take the control and make the default value as auto increment for us.