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