0

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 :)

abhihello123
  • 1,668
  • 1
  • 22
  • 38

1 Answers1

1

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);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Hi @Nizet, a slight error I correct in this part "company.setGCompanyId(7);" There could be 2 cases - 1)G_Company_ID already exists (like in this case 7 exists). Here is the part "company.getCPDocs().add(cpDoc);" necessary? I assumed it would happen implicitly since we add company to cpDoc in this code "cpDoc.setCompany(company);" 2)When G_Company_id is not in the db - Here do we have to do a new Company() like the code in my Question? (After out find() is unsuccessful) – abhihello123 Jun 08 '12 at 08:05
  • 1
    1. It's not absolutely necessary, but if you want a consistent object graph, you have to maintain it yourself. For example, if you keep using the company in the same session, and you hope finding the new CPDoc in its collection, it won't be there. It will be there only when you reload the company from the database, in a new session. 2. Yes, if the company does not exist, you need to create it and persist it. – JB Nizet Jun 08 '12 at 08:12
  • +1 for the clear explanation in the answer as well as comment :) – abhihello123 Jun 08 '12 at 11:21