Hibernate更新object中的所有列

时间:2012-10-14 11:46:50

标签: java hibernate

我有以下方法使用hibernate更新数据库中的行。我想使用新对象更新表中的所有列。因此,我获取现有对象并将其所有属性设置为新对象的属性。

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

在这个方法中,我逐个更新所有列,如果我有一天添加新列,我必须记住更改此方法。

place.setPhone(newPlace.getPhone());
place.setPKey(newPlace.getPKey()); 
place.setName(newPlace.getName());
place.setDetails(newPlace.getDetails());

使用newPlace对象更新列是否有更短的方法?

1 个答案:

答案 0 :(得分:1)

你最好在会话界面中使用get方法获取对象,然后更新对象的属性,然后使用update方法。 即

Place place = (Place)session.get(newPlace.getId());
place.setPhone(newPlace.getPhone());
....

session.update(place);