Assume that the following record exists in a table in Oracle database:
CustomerId CustName City
1001 John Mumbai
Consider the below code (assuming session factory is created and session is open):
//retrieving the object from database which also brings the entity in managed state
Customer cust1 = (Customer)session.get(Customer.class,1001); //Line 1
//modification to the object state in heap
cust1.setCustomerId(1002);
cust1.setCustomerName(“Mark”);
cust1.setCity(“Mysore”);
//getting the latest state of object from database back to heap
session.refresh(cust1); //Line 2
syso(cust1.getCustomerId()); //Line 3
syso(cust1.getCustomerName()); //Line4
syso(cust1.getCity()); //Line5
O/p:
Line 3: 1002
Line 4: John
Line 5: Mumbai
I was surprised to see the output of “Line 3” because according to the functionality of refresh() method, it fetches the current state of object from database back to heap memory. But it was unable to refresh the Primary key of the object although in database it is still 1001.
As we can see in the output, it is able to fetch the value of all other attributes but not the primary key
I even checked by using “show_sql” true in hibernate.xml that at line 2, it is making a query to the database to fetch all the attributes including the primary key but still for some reason it is not able to update the value of the primary key.
Please help me understand the behavior of refresh() method of hibernate