JpaSystemException: attempted to assign id from null one-to-one property - spring

I'm using the Play framework with Spring and Hibernate, and I get the following error when I try to save an entity containing a one-to-one relationship to another entity
[play] Caused by: org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [org.famian.web.models.domains.StudyCriteria.ensatIdent]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [org.famian.web.models.domains.StudyCriteria.ensatIdent]
[play] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:244) ~[spring-orm-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:155) ~[spring-orm-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) ~[spring-orm-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] Caused by: org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [org.famian.web.models.domains.StudyCriteria.ensatIdent]
[play] at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:98) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.jpa.event.internal.core.JpaMergeEventListener.saveWithGeneratedId(JpaMergeEventListener.java:73) ~[hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:271) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:251) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
The 2 entities share a common primary key, below are my classes
#Entity
public class EnsatIdent implements Serializable {
#EmbeddedId
private EnsatIdentPK id;
#OneToOne(mappedBy = "ensatIdent", cascade = CascadeType.ALL)
private StudyCriteria studyCriteria;
}
#Entity
public class StudyCriteria {
#EmbeddedId
private EnsatIdentPK id;
#MapsId
#JoinColumns({
#JoinColumn(name = "center_id"),
#JoinColumn(name = "ensat_id")
})
#OneToOne
private EnsatIdent ensatIdent;
}
#Embeddable
public class EnsatIdentPK implements Serializable {
#Column(name = "center_id", columnDefinition = "varchar(5)")
private String centerId;
#Column(name = "ensat_id", columnDefinition = "int(11)")
private Integer ensatId;
}
My service class is a class called IdenService which extending the Spring PagingAndSortingRepository class. When I save, I called
IdenService service.save(ensatIdent)
If I do a System.out.println() on
ensatIdent.getStudyCriteria()
it shows
StudyCriteria(id=EnsatIdentPK(centerId=GYMU, ensatId=3))
It saves fine if the entity only contain Ident information, but if I add studyCriteria in the object, the error will occur. I don't understand what is happening, please help.

Solved, the problem was because StudyCriteria object does not have a reference of the EnsatIden object.
By adding
ensatIdent.getStudyCriteria().setEnsatIdent(ensatIdent);
solved the error

Related

Duplicate or Null error when trying to send POST request for JSON Object with Foreign Key using Spring JPA

Here's my parent entity:
#Entity(name = "DrivingInstructor")
#Table(name = "driving_instructor")
#Getter
#Setter
#NoArgsConstructor
public class DrivingInstructor {
#Id
#Column(name = "driving_instructor_id")
private long drivingInstructorId;
#Column(name = "driving_instructor_name")
#Size(max = 128)
private String drivingInstructorName;
#Column(name = "specialization")
#Size(max = 200)
private String specialisation;
}
And here's my supposed child entity:
#Entity(name = "DrivingStudent")
#Table(name = "driving_student")
#Getter
#Setter
#NoArgsConstructor
public class DrivingStudent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "driving_student_id")
private long drivingStudentId;
#Column(name = "driving_student_name")
#Size(max = 128)
private String drivingStudentName;
#ManyToOne(cascade = CascadeType.ALL, targetEntity = DrivingInstructor.class)
#JoinColumn(name = "driving_instructor_id", referencedColumnName = "driving_instructor_name", insertable = false, updatable = false)
private DrivingInstructor drivingInstructor;
}
Here's the relevant chunk of my service class for inserting/saving an instance of a DrivingStudent into the database:
#RequestMapping(path = "api/v0/driving-school")
#RestController
#AllArgsConstructor
public class DrivingStudentRestController {
private final DrivingStudentServiceImpl drivingStudentServiceImpl;
#PostMapping
Long insertOrUpdateDrivingStudent(#Valid #RequestBody DrivingStudent drivingStudent) {
return drivingStudentServiceImpl.insertOrUpdateDrivingStudent(drivingStudent);
}
}
DrivingStudentServiceImpl is just an abstraction layer for Repository class that extends JpaRepository<DrivingStudent, Long>, so insertOrUpdateDrivingStudent() is practically just using the save() method from CrudRepository.
An instance of DrivingInstructor is already pre-inserted with drivingInstructorId of 1, and so I tried to execute a POST request via Postman using this JSON object:
{
"drivingStudentName": "Peter Parker",
"drivingInstructor": {"drivingInstructorId": 1}
}
And I'm getting this exception:
2021-08-27 20:03:37.554 ERROR 16108 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper :
ERROR: duplicate key value violates unique constraint "driving_instructor_pkey"
Detail: Key (driving_instructor_id)=(1) already exists.
2021-08-27 20:03:37.590 ERROR 16108 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] :
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException:
could not execute statement; SQL [n/a];
constraint [driving_instructor_pkey];
nested exception is org.hibernate.exception.ConstraintViolationException:
could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "driving_instructor_pkey"
Detail: Key (driving_instructor_id)=(1) already exists.
I also tried revising my RestController's PostMapping to look like this, but still nothing changes:
#RequestMapping(path = "api/v0/driving-school")
#RestController
#AllArgsConstructor
public class DrivingStudentRestController {
private final DrivingInstructorRepository drivingInstructorRepository;
private final DrivingStudentServiceImpl drivingStudentServiceImpl;
#PostMapping
Long insertOrUpdateDrivingStudent(#Valid #RequestBody DrivingStudent drivingStudent) {
Optional<DrivingInstructor> drivingInstructor = drivingInstructorRepository.findById(drivingStudent.getDrivingInstructor().getDrivingInstructorId());
if (drivingInstructor.isPresent()) {
drivingStudent.setDrivingInstructor(drivingInstructor.get());
return drivingStudentServiceImpl.insertOrDrivingStudent(drivingStudent);
}
return null;
}
}
The error I am getting then changed to:
2021-08-27 21:36:58.622 ERROR 11388 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper :
ERROR: null value in column "driving_instructor_number" of relation "driving_student" violates not-null constraint
Detail: Failing row contains (Peter Parker, null).
2021-08-27 21:36:58.632 ERROR 11388 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] :
Servlet.service() for servlet [dispatcherServlet] in context with path []
threw exception [Request processing failed;
nested exception is org.springframework.dao.DataIntegrityViolationException:
could not execute statement; SQL [n/a];
constraint [driving_instructor_number" of relation "driving_student];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: null value in column "driving_instructor_number" of relation "driving_student" violates not-null constraint
Detail: Failing row contains (Peter Parker, null).
There are stuff I've tried but most exceptions simply end up with either of those two. All I really wanted to do was insert an instance of DrivingStudent into the database using POST request, with a foreign key connecting it to a DrivingInstructor instance, and then of course, be able to retrieve those data.
I am able to do insert data manually into the database using the statement:
INSERT INTO driving_student VALUES ('Peter Parker', 1);
And I am able to retrieve that data in JSON format using GET method. So far, my only problem really is how to deal with the POST method.
Ok, I just changed/simplified the annotations in DrivingStudent's drivingInstructor JoinColumn field from this:
#ManyToOne(cascade = CascadeType.ALL, targetEntity = DrivingInstructor.class)
#JoinColumn(name = "driving_instructor_id", referencedColumnName = "driving_instructor_name", insertable = false, updatable = false)
private DrivingInstructor drivingInstructor;
to this:
#ManyToOne
#JoinColumn(name = "driving_instructor_id")
private DrivingInstructor drivingInstructor;
and it somehow worked... I have no idea why though.

Spring JPA Repository - Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet

I have a Repository and hitting directly this repository from Postman.
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
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.extract(ResultSetReturnImpl.java:79)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2115)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1874)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2610)
at org.hibernate.loader.Loader.doList(Loader.java:2593)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2422)
at org.hibernate.loader.Loader.list(Loader.java:2417)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1980)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:114)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:78)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:102)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:92)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 98 common frames omitted
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=RCON411.PROJECT, DRIVER=4.11.69
at com.ibm.db2.jcc.am.gd.a(gd.java:676)
at com.ibm.db2.jcc.am.gd.a(gd.java:60)
at com.ibm.db2.jcc.am.gd.a(gd.java:127)
at com.ibm.db2.jcc.am.jn.c(jn.java:2561)
at com.ibm.db2.jcc.am.jn.d(jn.java:2549)
at com.ibm.db2.jcc.am.jn.a(jn.java:2025)
at com.ibm.db2.jcc.am.kn.a(kn.java:6836)
at com.ibm.db2.jcc.t4.cb.g(cb.java:140)
at com.ibm.db2.jcc.t4.cb.a(cb.java:40)
at com.ibm.db2.jcc.t4.q.a(q.java:32)
at com.ibm.db2.jcc.t4.rb.i(rb.java:135)
at com.ibm.db2.jcc.am.jn.ib(jn.java:1996)
at com.ibm.db2.jcc.am.kn.sc(kn.java:3058)
at com.ibm.db2.jcc.am.kn.b(kn.java:3841)
at com.ibm.db2.jcc.am.kn.fc(kn.java:702)
at com.ibm.db2.jcc.am.kn.executeQuery(kn.java:672)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:82)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:82)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
... 127 common frames omitted
Project class is
#Data #Entity #Table(name = "PROJECT", schema = "DCS") public class Project implements Identifiable<Integer> {
#Id
#Column(name = "PRJ_I", nullable = false)
private Integer id;
#Column(name = "PRJ_NM")
private String projectName;
#OneToOne
#JoinColumn(name="PRJ_I")
private CcpaCustomerProjectGroup ccpaCustomerProjectGroup;
}
CcpaCustomerProjectGroup is
#Data #Entity #Table(name = "CCPA_CUS_PRJ_GRP", schema = "DCS") public class CcpaCustomerProjectGroup implements Identifiable<Integer> {
#Id
#Column(name="CCPA_CUS_PRJ_GRP_I")
private Integer id;
#Column(name="CUS_PRJ_GRP_I")
private Integer customerProjectGroupId;
#Column(name="PRJ_I")
private Integer projectId;
/*#OneToOne
#PrimaryKeyJoinColumn
private Project project;*/
}
ProjectRepository is
public interface ProjectRepository extends JpaRepository<Project, Integer>,JpaSpecificationExecutor<Project>, QueryDslPredicateExecutor<Project> {
#Query(value="select p.PRJ_I,p.PRJ_NM from CCPA_CUS_PRJ_GRP c,project p where c.CUS_PRJ_GRP_I = ?1 and c.PRJ_I = p.PRJ_I and p.PRJ_NM like ?2", nativeQuery = true)
List<Project> find(#Param("clientId") Integer clientId, #Param("projectName") String projectName);
}
As already stated by JB in the comments, this is the important part of the stack trace:
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=RCON411.PROJECT, DRIVER=4.11.69
First confirm that DCS.PROJECT exists in the datasource you are working with, and that the user you are connecting with in your application has the necessary grants to view it.
Similarly, Looks like the PROJECT table might be trying to get accessed from the wrong schema. Does the user you are using to connect to DB2 in your app have access to the DCS schema? And if so, you may need to set the CURRENT_SCHEMA to be DCS.

SQL0913 Row or object table in Schema type *FILE in use

I am having a transaction using spring data , and I am trying to do an save operation (insert operation) . [SQL0913] Row or object table in Schema type *FILE in use.
Following is the entity
#Entity
#IdClass(OsytxlId.class)
#Table(name="OSYTXL")
#NamedQuery(name="Osytxl.findAll", query="SELECT o FROM Osytxl o")
public class Osytxl implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="TLCONO")
private BigDecimal tlcono;
#Id
#Column(name="TLDIVI")
private String tldivi;
#Id
#Column(name="TLLINO")
private BigDecimal tllino;
#Column(name="TLLMTS")
private BigDecimal tllmts;
#Id
#Column(name="TLLNCD")
private String tllncd;
#Column(name="TLTX60")
private String tltx60;
#Id
#Column(name="TLTXID")
private BigDecimal tltxid;
#Id
#Column(name="TLTXVR")
private String tltxvr;
//getter and setters
}
I am using springdata-jpa
And I am calling the following code portion from the service implementation class
Before the following insertion , I need to delete the contents before insert .
Osytxl osytxl = null;
Collection<Osytxl> osytxlList = new ArrayList<Osytxl>();
for (int lineNo = 0; lineNo < lines.length; lineNo++) {
osytxl = new Osytxl();
osytxl.setTlcono(osytxh.getThcono());
osytxl.setTldivi(osytxh.getThdivi());
osytxl.setTltxid(osytxh.getThtxid());
osytxl.setTltxvr(osytxh.getThtxvr());
osytxl.setTllncd(osytxh.getThlncd());
osytxl.setTllmts(new BigDecimal("1437651510403"));
osytxl.setTllino(new BigDecimal(lineNo+1));
osytxl.setTltx60(lines[lineNo]);
osytxlList.add(osytxl);
}
if(osytxlList.size()>0)
osytxlRepository.save(osytxlList);
And I am using JPA repository But I am getting the following exception
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.GenericJDBCException: could not execute statement; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:415)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:418)
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$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
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:207)
at com.sun.proxy.$Proxy107.saveAndFlush(Unknown Source)
........................................................
Caused by: java.sql.SQLException: [SQL0913] Row or object OSYTXL in schema type *FILE in use.
at com.ibm.as400.access.JDError.createSQLExceptionSubClass(JDError.java:877)
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:706)
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:676)
at com.ibm.as400.access.AS400JDBCStatement.commonExecute(AS400JDBCStatement.java:1021)
at com.ibm.as400.access.AS400JDBCPreparedStatement.executeUpdate(AS400JDBCPreparedStatement.java:1825)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 127 more
I am using iseries (DB2) .Am I missing something or there anything I need to do extra in persistence.xml . Can anyone help .
I've found on Experts Exchange that this could be due to queries outside of your application, locking the required records.
Adding FOR READ ONLY to your query like this:
SELECT * FROM FILE.TABLE
FOR READ ONLY

Spring batch can't find entity persisted while processing

In one of our spring batch jobs, we create additional entities (CompanyProfile) during processing and persist them to the DB (in a separate transaction). These entities are referenced by other entities (Vacancy), which will be persisted by the writer, but unfortunate the writer fails with this error:
Caused by: javax.persistence.EntityNotFoundException: Unable to find com.company.CompanyProfile with id 1409881
The model is as follows:
#Entity
public class Vacancy {
#ManyToOne(fetch = FetchType.EAGER, optional = true)
#JoinColumn(name = "company", nullable = true)
private CompanyProfile company;
...
}
#Entity
public class CompanyProfile {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
}
In the processor we have this:
CompanyProfile company = companyProfileService.handleCompany(compName);
vacancy.setCompany(company);
Where the method companyProfileService.handleCompany() is annotated with #Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW )
I'm sure the CompanyProfile gets persisted - I can see it in the DB, but when the Vacancy gets saved by the ItemWriter, it fails with the above exception. (also, note that the id of the persisted entity is mention in the exception above)
Do you see any reason why the writer would fail in this case?
With information you gave us my guess is that transaction opened by SB is unable to see data persisted by companyProfileService.handleCompany() method because service component uses a different transaction than SB ones; you have to check database ISOLATION_LEVEL property

JPA unable to assign a new persisted entity in a many to one relationship

I have to JPA Entities defined with a bidirectional relationship many to one, hereby:
#Entity
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="DEPARTAMENTO_ID_GENERATOR",sequenceName="DEPARTAMENTO_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="DEPARTAMENTO_ID_GENERATOR")
#Column(name="DEP_ID")
private long id;
#Column(name="DEP_DESC")
private String desc;
//bi-directional many-to-one association to Academico
#OneToMany(mappedBy="department")
private Set<Proffesor> proffesors;
//getters and setters
}
#Entity
#Table(name="ACADEMICOS")
public class Proffesor implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="ACADEMICOS_ID_GENERATOR", sequenceName="ACADEMICOS_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="ACADEMICOS_ID_GENERATOR")
#Column(name="ACD_ID")
private long id;
#ManyToOne(cascade={CascadeType.PERSIST,CascadeType.MERGE})
#JoinColumn(name="ACD_DEPADSCRITO_DEP")
private Department department;
// getters and setters.
}
After in a transactional Spring service I have the next code to manipulate the entities in this way.
#Transactional (propagation=Propagation.REQUIRED)
public void createDepartmentWithExistentProffesor(String desc,Long idAvaiableProf) {
// new department
Department dep = new Department();
dep.setDesc(desc);
HashSet<Proffesor> proffesors = new HashSet<Proffesor>();
dep.setProffesors(proffesors);
// I obtain the correct attached Proffesor entity
Proffesor proffesor=DAOQueryBasic.getProffesorById(idAvaiableProf);
// I asign the relationship beetwen proffesor and department in both directions
dep.addProffesors(proffesor);
// Persists department
DAODataBasic.insertDepartment(dep);
// The id value is not correct then Exception ORA-0221
System.out.println("SERVICIO: Departamento creado con id: " + dep.getId());
}
As I said in the comments the id of the new Department persisted is not a real database id inside the transaction, then it is produced an exception
Exception in thread "main" org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
........
Caused by: java.sql.BatchUpdateException: ORA-02291: integrity restiction (HIBERNATE_PRB.FK_ACD2DEP) violated - primary key don't found
I've tried in a test, persist the new departmen entity with no relationship with Proffesor and I've seen that the id of the new department persisted entity has not a valid value inside the transaction but out of the transaction already the id has a correct value.
But I need the correct value inside the transaction.
Can anybody help me?
Thank you in advance.
try this
#OneToMany(mappedBy="department",cascade = CascadeType.PERSIST)
private Set<Proffesor> proffesors;

Resources