This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
I have just started to learn JPA and tried a simple program which inserts data into the table. one of the columns in the table has a primary key. I assume, JPA doesn't allow duplicate values and throws exception. ( My undersatnding might be wrong ). But I find the exception coming from DB, which means it reaches out to the DB and throws the error. Is this what actually happens ?
If one of the columns is a primary key the database will not allow duplicates, it will result in an exception being thrown. I cannot comment on what JPA will do, because you have not provided us with enough information. Please read TellTheDetails. Without knowing anything about how things are mapped we cannot give you any answers.
I have used @Id for one of the elements in the model.
Please read TellTheDetails. Without knowing anything about how things are mapped we cannot give you any answers.
I done have any exception or error. I just want to clarify my understanding here. so I haven't posted any of my codes.
I thought JPA stops up front when there is a duplicate record. Or probably it stops upfront when there is a duplicate record within the batch that is persisted at that moment. I would try this which struck me now, and post back.
The @Id on the object uniquely identify the object within the persistence context (it is in essence the primary key). Only one object with a given id can exist within the persistence context at a time. Now typically this will match the primary key and unique constraints on the table as well but this is not enforced.
The developer still needs to be smart about things.
Given the following scenario:
Table has a primary key column named Id.
Entity mapped to that table has an @Id field mapped to the column id in the table.
if you try to call entityManager.persist() on an entity with a particular id and that id already is present in the database, JPA will attempt to insert it and an exception will be thrown. There are other operations like merge for updating entities.