Reputation: 1166
I have the following method to update a row in database using hibernate. I want to update all the columns in the table using the new object. So I get the existing object and set all of its properties to the new object's properties.
public void updatePlace(Place newPlace) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Place place = (Place)session.createQuery("FROM Place AS plc WHERE plc.Id = " + newPlace.getId()).list().get(0);
place.setPhone(newPlace.getPhone());
place.setPKey(newPlace.getPKey());
place.setName(newPlace.getName());
place.setDetails(newPlace.getDetails());
session.update(place);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
In this method I update all the columns one by one, and if I add a new column one day I have to remember to change this method.
place.setPhone(newPlace.getPhone());
place.setPKey(newPlace.getPKey());
place.setName(newPlace.getName());
place.setDetails(newPlace.getDetails());
Is there a shorter way to update the columns using the newPlace object?
Upvotes: 1
Views: 916
Reputation: 624
you'd better get the object with using get method in session interface, and then update the properties of the object then use update method. i.e.
Place place = (Place)session.get(newPlace.getId());
place.setPhone(newPlace.getPhone());
....
session.update(place);
Upvotes: 1