I'm using:
Spring framework version: 3.2.2.RELEASE
hibernate version: 4.3.0.CR1
spring-data-jpa: 1.3.1.RELEASE
I have following classes:
Client
ClientInfo
Service
Each Client can have [0, N] ClientInfos (one-to-many). Each ClientInfo can have [0, N] Services. And for each ClientInfo-Service 'joint' I have an extra 'description' -field to describe the relationship. The 'joint'-class is called:
ClientInfoService
An example of resulting data structure:
Client
ClientInfo
ClientInfoService
Service
Description
ClientInfoService
Service
Description
ClientInfoService
Service
Description
Here are the codes for the classes:
#Entity
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
#OneToMany(mappedBy = "client", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ClientInfo> infos = new HashSet<ClientInfo>();
public Set<ClientInfo> getInfos() {
return infos;
}
public void setInfos(Set<ClientInfo> infos) {
this.infos.clear();
this.infos.addAll(infos);
for (Iterator<ClientInfo> iterator = infos.iterator(); iterator.hasNext();) {
ClientInfo item = iterator.next();
// update client relation to ClientInfo item because it is not necessarily up-to-date with the given input data
item.setClient(this);
}
}
}
#Entity
public class ClientInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
#ManyToOne
#JoinColumn(name = "client_id", nullable = false)
private Client client;
#OneToMany(mappedBy = "clientInfoService.client", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ClientInfoService> services = new HashSet<ClientInfoService>();
public Set<ClientInfoService> getServices() {
return services;
}
public void setServices(Set<ClientInfoService> services) {
this.services.clear();
this.services.addAll(services);
for (Iterator<ClientInfoService> iterator = services.iterator(); iterator.hasNext();) {
ClientInfoService item = iterator.next();
// update client info relation to ClientInfoService item because it is not necessarily up-to-date with the given input data
item.getClientInfoService().setClientInfo(this);
}
}
}
#Entity
public class Service {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
#OneToMany(mappedBy = "clientInfoService.service", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ClientInfoService> infoServices = new HashSet<ClientInfoService>();
#JsonIgnore
public Set<ClientInfoService> getInfoServices() {
return infoServices;
}
public void setInfoServices(Set<ClientInfoService> infoServices) {
this.infoServices.clear();
this.infoServices.addAll(infoServices);
for (Iterator<ClientInfoService> iterator = infoServices.iterator(); iterator.hasNext();) {
ClientInfoService item = iterator.next();
// update service relation to ClientInfoService item because it is not necessarily up-to-date with the given input data
item.getClientInfoService().setService(this);
}
}
}
#Entity
#Table(name = "clientInfo_service")
public class ClientInfoService {
#EmbeddedId
private ClientInfoServiceAssociationId clientInfoService;
#Column(name = "description", nullable = true, length = 200)
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ClientInfoServiceAssociationId getClientInfoService() {
return clientInfoService;
}
public void setClientInfoService(ClientInfoServiceAssociationId clientInfoService) {
this.clientInfoService = clientInfoService;
}
#Override
public int hashCode() {
if (this.clientInfoService != null) {
return this.clientInfoService.hashCode();
} else {
return 0;
}
}
#Embeddable
public class ClientInfoServiceAssociationId implements Serializable {
#ManyToOne
#JoinColumn(name = "clientInfo_id", nullable = false)
private ClientInfo clientInfo;
#ManyToOne
#JoinColumn(name = "service_id", nullable = false)
private Service service;
#JsonIgnore
public ClientInfo getClientInfo() {
return clientInfo;
}
public void setClientInfo(ClientInfo clientInfo) {
this.clientInfo = clientInfo;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
#Override
public boolean equals(Object obj) {
ClientInfoServiceAssociationId id = (ClientInfoServiceAssociationId) obj;
boolean cond = false;
boolean serv = false;
if (id.clientInfo != null && this.clientInfo != null && id.clientInfo.getId() == this.clientInfo.getId()) {
cond = true;
}
if (id.service != null && this.service != null && id.service.getId() == this.service.getId()) {
serv = true;
}
return cond && serv;
}
#Override
public int hashCode() {
int ret = 0;
if (this.clientInfo != null && this.clientInfo.getId() != null) {
ret += this.clientInfo.getId();
}
if (this.service != null) {
ret += this.service.getId();
}
return ret;
}
}
Everything works perfectly when saving clients with new infos without existing services. The problem case with this setup is:
Save client data with a new info (id: null) with links to existing services.
Following exception comes when calling saveAndFlush():
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: -177, SQLState: 23503
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - integrity constraint violation: foreign key no parent; FK_L5435O51W7YGX5N3NEJ84GN9V table: CLIENTINFO_SERVICE
ERROR: fi.loikka.nursebuddy.controller.GlobalControllerExceptionHandler - GENERAL ERROR!
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.ConstraintViolationException: could not execute statement; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy90.saveAndFlush(Unknown Source)
at fi.myCompany.component.update(ClientServiceImpl.java:130)
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
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.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy92.update(Unknown Source)
at fi.myCompany.component2.updateClient(ClientController.java:107)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:849)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:691)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at fi.myCompany.security.TokenFilter.doFilterInternal(TokenFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:134)
at fi.myCompany.component.Test.addClientInfoWithService(ClientControllerTest.java:426)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
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.maven.surefire.util.ReflectionUtils.invokeMethodWithArray2(ReflectionUtils.java:208)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:159)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:87)
at org.apache.maven.plugin.surefire.InPluginVMSurefireStarter.runSuitesInProcess(InPluginVMSurefireStarter.java:83)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:793)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:703)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:631)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
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.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1770)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1684)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1690)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1345)
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.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at com.sun.proxy.$Proxy76.flush(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.flush(SimpleJpaRepository.java:397)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.saveAndFlush(SimpleJpaRepository.java:365)
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.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:333)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
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.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
... 125 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:74)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:61)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3123)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3586)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:103)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:453)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:345)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1167)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1342)
... 145 more
Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: foreign key no parent; FK_L5435O51W7YGX5N3NEJ84GN9V table: CLIENTINFO_SERVICE
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
... 155 more
Caused by: org.hsqldb.HsqlException: integrity constraint violation: foreign key no parent; FK_L5435O51W7YGX5N3NEJ84GN9V table: CLIENTINFO_SERVICE
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.Constraint.getException(Unknown Source)
at org.hsqldb.Constraint.checkInsert(Unknown Source)
at org.hsqldb.StatementDML.performIntegrityChecks(Unknown Source)
at org.hsqldb.StatementDML.insertSingleRow(Unknown Source)
at org.hsqldb.StatementInsert.getResult(Unknown Source)
at org.hsqldb.StatementDMQL.execute(Unknown Source)
at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 158 more
Test case
#Test
#DatabaseSetup(value = "clientcontroller/clientcontrollertestdata_client_with_infos.xml", type = DatabaseOperation.CLEAN_INSERT)
#ExpectedDatabase(value = "clientcontroller/clientcontrollertestdata_client_add_infos_after.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void addClientInfoWithService() throws Exception {
datasource.getConnection().prepareStatement("SET DATABASE REFERENTIAL INTEGRITY TRUE").execute();
Client client = createTestClient( ...);
HashSet<ClientInfo> infos = new HashSet<ClientInfo>();
ClientInfo info1 = new ClientInfo( … );
info1.setId(1l);
Service service1 = new Service( … );
service1.setId(1l);
ClientInfo info2 = new ClientInfo( … );
ClientInfoServiceAssociationId compoundKey = new ClientInfoServiceAssociationId();
compoundKey.setClientInfo(info2);
compoundKey.setService(service1);
ClientInfoService clientInfoNew = new ClientInfoService();
clientInfoNew.setDescription("new description");
clientInfoNew.setClientInfoService(compoundKey);
HashSet<ClientInfoService> set = new HashSet<ClientInfoService>();
set.add(clientInfoNew);
info2.setServices(set);
service1.setInfoServices(set);
infos.add(info1);
infos.add(info2);
client.setInfos(infos);
String resultJSON = jsonConverter.convertToJSON(client);
mockMvc.perform(put("/clients/1").header("headertoken", this.token).content(resultJSON).contentType(MediaType.APPLICATION_JSON)).andExpect(
status().isNoContent());
}
What could be the problem? Something in my entity definions?
Related
I am having the following problem. I have pushed my example into GitHub.
If I want to persist an instance of my class PlayerStatistics then Hibernate tries to create an already existing entity of Matchday (specified as #ManyToOne) which I do not want to but I do not seem to get around it.
I am persisting in the init method of DemoApplicationTests.
#Before
public void init() {
final Matchday matchday = matchdayRepository.save(new Matchday(1));
final Club club1 = clubRepository.save(new Club("Klub1"));
final Club club2 = clubRepository.save(new Club("Klub2"));
final Match match = matchRepository.save(new Match(matchday, club1, club2));
final Player player = playerRepository.save(new Player(1, "Jan", "Kowalski", club1));
playerStatisticsRepository.save(new PlayerStatistics(matchday, player, match));
}
If I have it like above, then I get the following exception.
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [SYS_PK_10114]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
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)
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.$Proxy102.save(Unknown Source)
at com.example.DemoApplicationTests.init(DemoApplicationTests.java:49)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2934)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3434)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:582)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:456)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1407)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:477)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3170)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2384)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
... 44 more
Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: unique constraint or index violation; SYS_PK_10114 table: MATCHDAY
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 62 more
Caused by: org.hsqldb.HsqlException: integrity constraint violation: unique constraint or index violation; SYS_PK_10114 table: MATCHDAY
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.Constraint.getException(Unknown Source)
at org.hsqldb.index.IndexAVLMemory.insert(Unknown Source)
at org.hsqldb.persist.RowStoreAVL.indexRow(Unknown Source)
at org.hsqldb.TransactionManager2PL.addInsertAction(Unknown Source)
at org.hsqldb.Session.addInsertAction(Unknown Source)
at org.hsqldb.Table.insertSingleRow(Unknown Source)
at org.hsqldb.StatementDML.insertSingleRow(Unknown Source)
at org.hsqldb.StatementInsert.getResult(Unknown Source)
at org.hsqldb.StatementDMQL.execute(Unknown Source)
at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 65 more
If I debug the HQL I can clearly see that Hibernate wants to insert a new row into the table Matchday even if it already exists.
Hibernate:
insert
into
Matchday
(matchdayNumber)
values
(?)
If I comment the last line of the init() method then it works OK, so the problem has to be in this part: playerStatisticsRepository.save(new PlayerStatistics(matchday, player, match))
#Before
public void init() {
final Matchday matchday = matchdayRepository.save(new Matchday(1));
final Club club1 = clubRepository.save(new Club("Klub1"));
final Club club2 = clubRepository.save(new Club("Klub2"));
final Match match = matchRepository.save(new Match(matchday, club1, club2));
final Player player = playerRepository.save(new Player(1, "Jan", "Kowalski", club1));
//playerStatisticsRepository.save(new PlayerStatistics(matchday, player, match));
}
What am I doing wrong here?
PlayerStatistics class looks like that.
#Entity
#IdClass(PlayerStatisticsId.class)
public class PlayerStatistics implements Serializable {
//...
#Id
#ManyToOne(optional = false)
#PrimaryKeyJoinColumn
private Player player;
#Id
#ManyToOne(optional = false)
#PrimaryKeyJoinColumn
private Matchday matchday;
#ManyToOne(optional = false)
#JoinColumns({ #JoinColumn(name = "matchday_matchdaynumber", referencedColumnName = "matchday_matchdaynumber"),
#JoinColumn(name = "hometeam_name", referencedColumnName = "hometeam_name") })
private Match match;
#Column(nullable = false)
private boolean playedFromTheFirstWhistleblow;
#Min(0)
#Column(nullable = false)
private int enteredTheFieldAtInSeconds;
#Min(0)
#Column(nullable = false)
private int leftTheFieldAtInSeconds;
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable
#MapKeyEnumerated(EnumType.STRING)
private Map<ScoreType, Integer> statistics = new HashMap<>();
//...
}
EDIT
If I want to manage it directly from the Player entity on the other hand. Then I receive an exception that the entity is already associated with the session, while it does not seem to be.
#Before
public void init() {
final Matchday matchday = matchdayRepository.save(new Matchday(1));
final Club club1 = clubRepository.save(new Club("Klub1"));
final Club club2 = clubRepository.save(new Club("Klub2"));
final Match match = matchRepository.save(new Match(matchday, club1, club2));
final Player player = new Player(1, "Jan", "Kowalski", club1);
player.addPlayerStatistics(new PlayerStatistics(matchday, player, match));
playerRepository.save(player);
}
org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [com.example.model.Player#1]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.example.model.Player#1]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:410)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:246)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
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.$Proxy99.save(Unknown Source)
at com.example.DemoApplicationTests.init(DemoApplicationTests.java:49)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.example.model.Player#1]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:116)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:899)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:855)
at org.hibernate.engine.spi.CascadingActions$6.cascade(CascadingActions.java:261)
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.cascadeCollectionElements(Cascade.java:424)
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:356)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:319)
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.cascadeAfterSave(AbstractSaveEventListener.java:445)
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:238)
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:300)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:169)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:68)
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:864)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:845)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:850)
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:298)
at com.sun.proxy.$Proxy97.merge(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:509)
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.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:282)
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)
... 37 more
The problem here was in the PlayerStatisticsId and the way it was defined.
Originally it looked like this.
public class PlayerStatisticsId implements Serializable {
//..
private long player;
private int matchday;
public long getPlayer() {
return player;
}
public int getMatchday() {
return matchday;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof PlayerStatisticsId) {
final PlayerStatisticsId o = (PlayerStatisticsId) obj;
return o.matchday == matchday && o.player == player;
} else {
return false;
}
}
}
I could have sworn that I read somewhere that only the primitives/basic types could be used in a class that is used for #ClassId. It does not seem to be the case though.
After changing it to
public class PlayerStatisticsId implements Serializable {
//...
private Player player;
private Matchday matchday;
public Player getPlayer() {
return player;
}
public Matchday getMatchday() {
return matchday;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof PlayerStatisticsId) {
final PlayerStatisticsId o = (PlayerStatisticsId) obj;
return o.matchday.equals(matchday) && o.player.equals(player);
} else {
return false;
}
}
}
It does seem to work. I am receiving a completely different exception now but it is a case for a separate question.
I have a table relationship similar to the one described in this question I tried the way they said they'd fixed it there. Got this could not initialize a collection error. I looked around and changed it to have a third entity and the two original classes having Set with OneToMany mapping to that entity as opposed to using Map and ManyToMany mapping.
In case I'm just missing something stupid right in front of my face, here are my tables:
create table email_distribution_templates (
id number primary key,
from_address varchar2(50) not null,
subject varchar2(250) not null,
body varchar2(4000),
send_time date,
send_type varchar2(10),
email_type varchar2(50),
attachments_by varchar2(10),
attachment_info varchar2(50),
last_sent date,
CONSTRAINT unique_email_subject UNIQUE (subject)
);
create sequence distro_seq CACHE 50;
create table email_distribution_addressees (
id number primary key,
first_name varchar2(50),
last_name varchar2(50),
address varchar2(100) not null
);
create sequence addressee_seq CACHE 50;
create table addressees_for_distributions (
distro_id number not null references email_distribution_templates(id),
addressee_id number not null references email_distribution_addressees(id),
addressee_type varchar2(3) not null,
constraint adrs_fr_dist primary key(distro_id, addressee_id)
);
create sequence ad_fr_dst_seq CACHE 50;
And here are their corresponding entities:
#Entity
#Table(name = "email_distribution_templates")
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#SequenceGenerator(sequenceName = "distro_seq", name = "distro_seq", allocationSize = 1)
#Configurable(autowire = Autowire.BY_TYPE)
public class EmailDistributionTemplate implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "distro_seq")
private long id;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "distro")
private Set<AddresseeForDistribution> addresseeForDistribution = Sets.newHashSet();
#NotNull
Email
private String fromAddress;
#NotNull
private String subject;
private String body;
private DateTime sendTime;
Enumerated(EnumType.STRING)
private SendTimeType sendType;
#Enumerated(EnumType.STRING)
private EmailType emailType;
#Enumerated(EnumType.STRING)
private AttachmentsBy attachmentsBy;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "email")
private Set<EmailSent> emailSentTimes = Sets.newHashSet();
private DateTime lastSent;
private String attachmentInfo;
#Transient
private List<String> attachments = new ArrayList<String>();
#Transient
private String tempBody;
//getters and setters
}
#Entity
#Table(name = "email_distribution_addressees")
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#SequenceGenerator(sequenceName = "addressee_seq", name = "addressee_seq", allocationSize = 1)
#Configurable(autowire = Autowire.BY_TYPE)
public class EmailDistributionAddressee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "addressee_seq")
private long id;
#OneToMany(mappedBy = "addressee")
private Set<AddresseeForDistribution> addresseeForDistribution = Sets.newHashSet();
#Email
#NotNull
private String address;
private String firstName;
private String lastName;
//getters and setters
}
This is the entity that it is having problems forming a Set of in the EmailDistributionTemplate class:
#Entity
#Table(name = "addressees_for_distributions")
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#Configurable(autowire = Autowire.BY_TYPE)
public class AddresseeForDistribution implements Serializable {
private static final long serialVersionUID = 1L;
// #EmbeddedId
// private Id id;
#Id
private long id;
#ManyToOne(optional = false)
#JoinColumn(name = "distro_id", referencedColumnName = "id", insertable = false, updatable = false)
private EmailDistributionTemplate distro;
#ManyToOne(optional = false)
#JoinColumn(name = "addressee_id", referencedColumnName = "id", insertable = false, updatable = false)
private EmailDistributionAddressee addressee;
#Column(name = "addressee_type")
private AddresseeType addresseeType;
//getters and setters
}
As you can see, there are some commented out bits related to an embedded ID, I was getting the same error with that, so I thought I'd try without.
And here's the stacktrace:
Hibernate: select addresseef0_.distro_id as distro_i4_12_1_, addresseef0_.id as id1_0_1_, addresseef0_.id as id1_0_0_, addresseef0_.addressee_id as addresse3_0_0_, addresseef0_.addressee_type as addresse2_0_0_, addresseef0_.distro_id as distro_i4_0_0_ from addressees_for_distributions addresseef0_ where addresseef0_.distro_id=?
13018 [main] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 17059, SQLState: 99999
13018 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - Fail to convert to internal representation
13028 [main] WARN o.h.e.loading.internal.LoadContexts - HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext#37e79b10<rs=org.apache.commons.dbcp.DelegatingResultSet#144e1c6e>
13028 [main] WARN o.h.e.l.i.CollectionLoadContext - HHH000160: On CollectionLoadContext#cleanup, localLoadingCollectionKeys contained [1] entries
13038 [main] ERROR o.s.batch.core.step.AbstractStep - Encountered an error executing step processEmailStep in job sendEmailJob
org.springframework.batch.core.step.skip.NonSkippableReadException: Non-skippable exception during read
at org.springframework.batch.core.step.item.FaultTolerantChunkProvider.read(FaultTolerantChunkProvider.java:104) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:114) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:108) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:395) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:267) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:77) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:253) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:141) [spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:380) [spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:124) [spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:301) [spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:134) [spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:127) [spring-batch-core-2.2.7.RELEASE.jar:na]
at com.stuff.my.app.email.SendEmailJobITest.sendEmail(SendEmailJobITest.java:58) [test-classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.6.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.6.0_45]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.6.0_45]
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) [junit-4.11.jar:na]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.11.jar:na]
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) [junit-4.11.jar:na]
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:309) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) [spring-test-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [.cp/:na]
Caused by: org.springframework.orm.jpa.JpaSystemException: could not initialize a collection: [com.stuff.my.app.email.EmailDistributionTemplate.addresseeForDistribution#-1]; nested exception is org.hibernate.exception.GenericJDBCException: could not initialize a collection: [com.stuff.my.app.email.EmailDistributionTemplate.addresseeForDistribution#-1]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:244) ~[spring-orm-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:155) ~[spring-orm-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) ~[spring-orm-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92) ~[spring-data-jpa-1.3.4.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at com.sun.proxy.$Proxy113.findNotSentBySendTime(Unknown Source) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.6.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.6.0_45]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.6.0_45]
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:269) ~[spring-core-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.batch.item.data.RepositoryItemReader.doInvoke(RepositoryItemReader.java:243) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.item.data.RepositoryItemReader.doPageRead(RepositoryItemReader.java:208) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.item.data.RepositoryItemReader.doRead(RepositoryItemReader.java:153) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:83) ~[spring-batch-infrastructure-2.2.7.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.6.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.6.0_45]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.6.0_45]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at com.sun.proxy.$Proxy111.read(Unknown Source) ~[na:na]
at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:91) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
at org.springframework.batch.core.step.item.FaultTolerantChunkProvider.read(FaultTolerantChunkProvider.java:87) ~[spring-batch-core-2.2.7.RELEASE.jar:na]
... 51 common frames omitted
Caused by: org.hibernate.exception.GenericJDBCException: could not initialize a collection: [com.stuff.my.app.email.EmailDistributionTemplate.addresseeForDistribution#-1]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.loadCollection(Loader.java:2267) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.collection.LegacyBatchingCollectionInitializerBuilder$LegacyBatchingCollectionInitializer.initialize(LegacyBatchingCollectionInitializerBuilder.java:100) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:674) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:86) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1774) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:681) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:1030) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:353) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2548) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2534) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2364) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.list(Loader.java:2359) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:357) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1194) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:268) ~[hibernate-entitymanager-4.2.8.Final.jar:4.2.8.Final]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:108) ~[spring-data-jpa-1.3.4.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:55) ~[spring-data-jpa-1.3.4.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:95) ~[spring-data-jpa-1.3.4.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:85) ~[spring-data-jpa-1.3.4.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:312) ~[spring-data-commons-1.5.2.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.0.4.RELEASE.jar:4.0.4.RELEASE]
... 81 common frames omitted
Caused by: java.sql.SQLException: Fail to convert to internal representation
at oracle.jdbc.driver.CharCommonAccessor.getInt(CharCommonAccessor.java:147) ~[ojdbc6-11.2.0.3.jar:11.2.0.3.0]
at oracle.jdbc.driver.T4CVarcharAccessor.getInt(T4CVarcharAccessor.java:828) ~[ojdbc6-11.2.0.3.jar:11.2.0.3.0]
at oracle.jdbc.driver.OracleResultSetImpl.getInt(OracleResultSetImpl.java:942) ~[ojdbc6-11.2.0.3.jar:11.2.0.3.0]
at oracle.jdbc.driver.OracleResultSet.getInt(OracleResultSet.java:434) ~[ojdbc6-11.2.0.3.jar:11.2.0.3.0]
at org.apache.commons.dbcp.DelegatingResultSet.getInt(DelegatingResultSet.java:275) ~[commons-dbcp-1.4.jar:1.4]
at org.apache.commons.dbcp.DelegatingResultSet.getInt(DelegatingResultSet.java:275) ~[commons-dbcp-1.4.jar:1.4]
at org.hibernate.type.EnumType$OrdinalEnumValueMapper.getValue(EnumType.java:372) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2924) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1695) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1627) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.getRow(Loader.java:1509) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:719) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:949) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:917) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:348) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:318) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
at org.hibernate.loader.Loader.loadCollection(Loader.java:2260) ~[hibernate-core-4.2.8.Final.jar:4.2.8.Final]
... 109 common frames omitted
I think Hibernate is becoming the bane of my existence. Any ideas or help would be greatly appreciated. I've been Googling and tinkering and trying to fix this error for a few days now. I feel like it's probably something dumb that I'm overlooking.
I figured out the problem by having Hibernate create the tables for me and comparing them to my scripts and code. It was something dumb that was right in front of my face. I missed an annotation for an enum in AddresseesForDistribution
I put the following code in a main method to have Hibernate generate the table creation for me and output it to the log/console:
Configuration config = new Configuration();
config.addAnnotatedClass(AddresseeForDistribution.class);
config.addAnnotatedClass(EmailDistributionAddressee.class);
config.addAnnotatedClass(EmailDistributionTemplate.class);
config.addAnnotatedClass(EmailSent.class);
config.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
new SchemaExport(config).create(true,false); //the true tells it to output to the log/console, the false tells it to not actually touch the db
Thank you UweAllner for pointing me in that direction!
Hope you also declared mappings for annotated classes in hibernate.cfg.xml file.
Below is the model, service implementation and the error trace of my code.
Model class:
#Entity
#Table(name = "ph_diagnosis_history")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id",scope=Diagnosis.class)
public class Diagnosis extends AbstractEntity {
#Column(name = "diagnosis_notes", length=255)
#Length(max = 255, message = IprProp.MAX_LEN_255_MSG)
private String diagnosisNote;
#Enumerated(EnumType.STRING)
private DiagnosisTypeEnum type;
#Temporal(TemporalType.DATE)
#Column(name = "diagnosis_date")
#JsonSerialize(using = JsonDateSerializer.class)
private Date diagnosisDate;
#ManyToOne
#JoinColumn(name = "patient_chart_id")
private PatientChart patientChart;
public String getDiagnosisNote() {
return diagnosisNote;
}
public void setDiagnosisNote(String diagnosisNote) {
this.diagnosisNote = diagnosisNote;
}
public DiagnosisTypeEnum getType() {
return type;
}
public void setType(DiagnosisTypeEnum type) {
this.type = type;
}
public Date getDiagnosisDate() {
return diagnosisDate;
}
public void setDiagnosisDate(Date diagnosisDate) {
this.diagnosisDate = diagnosisDate;
}
public PatientChart getPatientChart() {
return patientChart;
}
public void setPatientChart(PatientChart patientChart) {
this.patientChart = patientChart;
}
}
My service:
public Diagnosis updateDiagnosis(IPRDTO clientDto, Long userId,
Long patientChartId, DiagnosisDTO diagnosisDTO, Long diagnosisId) throws Exception {
Diagnosis diagnosis = diagnosisRepository.findOne(diagnosisId);
if (diagnosis!=null){
if(diagnosis.getType().equals(DiagnosisTypeEnum.WORKING)){
BeanCopyUtil.copyProperties(diagnosisDTO, diagnosis, true);
return this.diagnosisRepository.saveAndFlush(diagnosis);
}
else{
throw new BusinessException("updateDiagnosisValidation");
}
}
throw new BusinessException("noDiagnosis");
}
My stack trace:
[2014-09-08 11:34:08,148] INFO com.zurelsoft.ipr.service.IDiagnosisService- Logged In User Id [1]:Started updateDiagnosis
diagnosis id 2
[2014-09-08 11:34:08,969] INFO org.hibernate.event.internal.DefaultLoadEventListener- HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
[2014-09-08 11:34:09,001] ERROR com.zurelsoft.ipr.service.IDiagnosisService- Logged In User Id [1]:Error Occurred updateDiagnosis
org.springframework.orm.jpa.JpaSystemException: org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis; nested exception is javax.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
[2014-09-08 11:34:09,006] ERROR com.zurelsoft.ipr.client.DiagnosisWebService- org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy85.findOne(Unknown Source)
com.zurelsoft.ipr.service.impl.DiagnosisServiceImpl.updateDiagnosis(DiagnosisServiceImpl.java:76)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:51)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy86.updateDiagnosis(Unknown Source)
com.zurelsoft.ipr.client.DiagnosisWebService.updateDiagnosis(DiagnosisWebService.java:98)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:849)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
I get this HibernateException in this line alhough my table has now two rows with the same id.
Diagnosis diagnosis = diagnosisRepository.findOne(diagnosisId);
Please anyone help me with my mistake. What can be probable error in my code.
Hy, It woks for me:
Seems I have two choices: either cascade all and delete orphan on the one-to-one relationship, or explicitly call my repository class to look up and save the original Sheet every time I remove its relationship with Plate. I opted for the first choice and added this to the plate class:
#OneToOne(mappedBy = "plate", cascade = CascadeType.ALL, orphanRemoval = true)
https://stackoverflow.com/a/32636186/3255595
From Spring documentation:
T findOne(ID id)
Retrieves an entity by its id.
Seem that diagnosisId is not a primary key.
it sounds like you have more than one row in the database with the same id values!
Are you sure your id is really unique in the DB ?
Hibernate Exception
More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
tells that hibernate query executes returns more than one row (i.e 2) of class Diagnosis Please enable SQL logging and execute the select by hand and see what it returns
WARNING: EJB5184:A system exception occurred during an invocation on EJB EmpFacade, method: public java.util.List com.session.AbstractFacade.findAll()
WARNING: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4475)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2009)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy243.findAll(Unknown Source)
at com.session.__EJB31_Generated__EmpFacade__Intf____Bean__.findAll(Unknown Source)
at com.control.EntityController.processRequest(EntityController.java:62)
at com.control.EntityController.doGet(EntityController.java:157)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.IllegalArgumentException: No [EntityType] was found for the key class [com.entity.Emp] in the Metamodel - please verify that the [Entity] class was referenced in persistence.xml using a specific <class>com.entity.Emp</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entityEmbeddableManagedTypeNotFound(MetamodelImpl.java:173)
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entity(MetamodelImpl.java:193)
at org.eclipse.persistence.internal.jpa.querydef.CommonAbstractCriteriaImpl.internalFrom(CommonAbstractCriteriaImpl.java:114)
at org.eclipse.persistence.internal.jpa.querydef.AbstractQueryImpl.from(AbstractQueryImpl.java:246)
at com.session.AbstractFacade.findAll(AbstractFacade.java:43)
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:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
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:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
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:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 34 more
WARNING: StandardWrapperValve[EntityController]: Servlet.service() for servlet EntityController threw exception
javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4475)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2009)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy243.findAll(Unknown Source)
at com.session.__EJB31_Generated__EmpFacade__Intf____Bean__.findAll(Unknown Source)
at com.control.EntityController.processRequest(EntityController.java:62)
at com.control.EntityController.doGet(EntityController.java:157)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.IllegalArgumentException: No [EntityType] was found for the key class [com.entity.Emp] in the Metamodel - please verify that the [Entity] class was referenced in persistence.xml using a specific <class>com.entity.Emp</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entityEmbeddableManagedTypeNotFound(MetamodelImpl.java:173)
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entity(MetamodelImpl.java:193)
at org.eclipse.persistence.internal.jpa.querydef.CommonAbstractCriteriaImpl.internalFrom(CommonAbstractCriteriaImpl.java:114)
at org.eclipse.persistence.internal.jpa.querydef.AbstractQueryImpl.from(AbstractQueryImpl.java:246)
at com.session.AbstractFacade.findAll(AbstractFacade.java:43)
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:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
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:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
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:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 34 more
Emp.java
#Entity
#Table(name = "EMP")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Emp.findAll", query = "SELECT e FROM Emp e"),
#NamedQuery(name = "Emp.findByEmpno", query = "SELECT e FROM Emp e WHERE e.empno = :empno"),
#NamedQuery(name = "Emp.findByEname", query = "SELECT e FROM Emp e WHERE e.ename = :ename"),
#NamedQuery(name = "Emp.findByJob", query = "SELECT e FROM Emp e WHERE e.job = :job"),
#NamedQuery(name = "Emp.findByMgr", query = "SELECT e FROM Emp e WHERE e.mgr = :mgr"),
#NamedQuery(name = "Emp.findByHiredate", query = "SELECT e FROM Emp e WHERE e.hiredate = :hiredate"),
#NamedQuery(name = "Emp.findBySal", query = "SELECT e FROM Emp e WHERE e.sal = :sal"),
#NamedQuery(name = "Emp.findByComm", query = "SELECT e FROM Emp e WHERE e.comm = :comm"),
#NamedQuery(name = "Emp.findByDeptno", query = "SELECT e FROM Emp e WHERE e.deptno = :deptno")})
public class Emp implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#NotNull
#Column(name = "EMPNO")
private BigDecimal empno;
#Size(max = 10)
#Column(name = "ENAME")
private String ename;
#Size(max = 9)
#Column(name = "JOB")
private String job;
#Column(name = "MGR")
private Short mgr;
#Column(name = "HIREDATE")
#Temporal(TemporalType.TIMESTAMP)
private Date hiredate;
#Column(name = "SAL")
private BigDecimal sal;
#Column(name = "COMM")
private BigDecimal comm;
#Column(name = "DEPTNO")
private Short deptno;
public Emp() {
}
public Emp(BigDecimal empno) {
this.empno = empno;
}
public BigDecimal getEmpno() {
return empno;
}
public void setEmpno(BigDecimal empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Short getMgr() {
return mgr;
}
public void setMgr(Short mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public BigDecimal getSal() {
return sal;
}
public void setSal(BigDecimal sal) {
this.sal = sal;
}
public BigDecimal getComm() {
return comm;
}
public void setComm(BigDecimal comm) {
this.comm = comm;
}
public Short getDeptno() {
return deptno;
}
public void setDeptno(Short deptno) {
this.deptno = deptno;
}
#Override
public int hashCode() {
int hash = 0;
hash += (empno != null ? empno.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Emp)) {
return false;
}
Emp other = (Emp) object;
if ((this.empno == null && other.empno != null) || (this.empno != null && !this.empno.equals(other.empno))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Emp[ empno=" + empno + " ]";
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="SampleBeanPU" transaction-type="JTA">
<jta-data-source>jdbc/OracleDS</jta-data-source>
<class>com.entity.Emp</class>
<class>com.entity.Dept</class>
<properties>
<property name="eclipselink.logging.level.sql" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
After each Clean and Build or Compiling of any file I'm getting above exception while accessing any page. To resolve this issue each time I have to restart the glassfish server. Since, this won't be good solution. So, anyone help me to resolve this issue ?
Restart the server then Clean, Build and Deploy your project this how i solved the problem
It seems I resolved my issue. I found this link
And added following code in my class where I'm creating instance of EMF
#PreDestroy
public void destruct()
{
emf.close();
}
and #override servlet destroy method and call above method. Now, It works.!!!
I'm a beginner, and got the same problem. After some days debugging I found out that my problem was the ID field in my MySQL table. It wasn't set as auto-increment. After changing that, problem solved.
Maybe it can be others beginners problem, too.
I have a class according to:
#Entity
public class Car {
#Id
#GeneratedValue
private Long id;
#NotNull
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "OWNER_ID")
private Owner owner;
#NotNull()
#Column(nullable = false)
private String make;
#NotNull()
#Column(nullable = true)
private String model;
#Column(nullable = false)
private String gears;
// More fields
Say I am trying to percist the object and one field, make field for instance, is null which is not supposed to be. Following exceptions is thrown:
WARNING: EJB5184:A system exception occurred during an invocation on EJB CarEJB, method: public se.while_se.domain.Car se.while_se.business.CarEJB.createCar(se.while_se.domain.Car)
Sep 09, 2012 12:37:37 PM com.sun.ejb.containers.BaseContainer postInvoke
WARNING:
javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at $Proxy137.createCar(Unknown Source)
at se.while_se.business.__EJB31_Generated__CarEJB__Intf____Bean__.createCar(Unknown Source)
at test.CarTest.populate(CarTest.java:197)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:45)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
What I would like to do is to find a best practice to validate the entity before persist it in the database. Sure, I could implement a help method inside the entity class something like:
public boolean validate() {
if(owner == null) {
return false;
}
if(make == null) {
return false;
}
if(model == null) {
return false;
}
return true;
}
But that does not feel as the right approach. Can you please guide me?
Best regards
You can and should validate the entity before persisting like this and return an appropriate error:
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Car>> constraintViolations = validator.validate(myCar);
if (constraintViolations.size() > 0) {
Set<String> violationMessages = new HashSet<String>();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
violationMessages.add(constraintViolation.getPropertyPath() + ": " + constraintViolation.getMessage());
}
throw new RuntimeException("Car is not valid:\n" + StringUtils.join(violationMessages, "\n"));
}