Search code examples
hibernatejpatransientpersist

Transient Exception using persist() method of JPA.. Doubts in persistence of entities.. Which side to persist?


First time I am using the persist() method in a project. With JPA I am using Hibernate as the provider. The case is pretty simple. I have 2 tables

  1. Company - Company_id (PK, a sequence), G_Company_id (Would also be unique)
  2. CP_Doc - Chronicle_id (PK), Company_id (FK to above Company_id))

Now I have some CP_Docs for some particular company. I have successfully created the entities (working for createNativeQuery, createQuery of JPA). I also have mentioned cascade = CASCADE.ALL for the collection.

For persisting I write the following code.

Company company = new Company();
    company.setGCompanyId(7);
    for(/* Get all docs for a particular company having id = 7 */) {
        CP_Doc cpDoc = new CP_Doc();
        cpDoc.setChronicleId(/* some chronicle id from the loop */);    
        cpDoc.setCompany(company);
        entityManager.persist(cpDoc);
    }

The relation between the tables is that one company can have many cp_docs. So CP_Doc table is the owner table. I tried persisting from CP_Doc side. Could I persist from Company Entity side also. Kindly help experts :)


Solution

  • If I understand correctly, you already have a company in database, with ID 7, and you try adding a CPDoc to this company.

    In this case, it makes little sense to persist the company, since it already exists. And it also makes no sense to create a new company, since it already exists. You should instead load the company from the database, and attach the company to the new CPDocs (and vice-versa):

    Company company = entityManager.find(Company.class, 7);
    for(...) {
        CP_Doc cpDoc = new CP_Doc();
        cpDoc.setChronicleId(...);    
        cpDoc.setCompany(company);
        company.getCPDocs().add(cpDoc);
        entityManager.persist(cpDoc);
    }