Friday, February 22, 2013

When does the JPA set a @GeneratedValue @Id


When does the JPA set a @GeneratedValue @Id


flush - During flush() JPA provider physically sends generated SQL to the database.

void flush()
Synchronize the persistence context to the underlying database.
Throws:
TransactionRequiredException - if there is no transaction
PersistenceException - if the flush fails





PatientDAO

@Override //HW5 - 1 the policy allows pid being null
public Long addPatient(String name, Date dob, int age) 
throws PatientExn {
DateFormat dateformat = new SimpleDateFormat("YYYY");
int birthyear = Integer.parseInt(dateformat.format(dob));
int currentyear = Integer.parseInt(dateformat.format(new Date()));
if(age!=(currentyear - birthyear)) throw new PatientExn("Inputed age conflic with birthday");
Patient patient = new Patient(); //this is another patient factory method
patient.setName(name);
patient.setBirthDate(dob);
em.persist(patient);
em.flush();  // now the patient object has Id that generated by DB.
long id = patient.getId(); 
//List<Patient> patients = this.getPatientByNameDob(name, dob);
//Patient patientThatJustInserted = patients.get(patients.size()-1);//get the latest one, which is just inserted 
//Long id = patientThatJustInserted.getId();
return id;
}




calling .persist() will not automatically set the id value. Your JPA provider will ensure that it is set before the entity is finally written to db. So you are right to assume that the id will be assigned when the transaction is committed. But this is not the only possible case. When you call .flush() the very same will happen.
Thomas

No comments:

Post a Comment