开发者

Hibernate-Spring how do I turn my save into a update or save?

Hibernate-Spring how do I turn my save into a update or save??

I am using the following code in my system but if a dealer with the same rUser is in the table I would like to update the row. how can I do this?

public void saveDealer(Dealer dealer, String rUser) {

    dealer.setUsername(rUser);
    dealer.setAddedDate(new Date());
    sessionFactory.getCurrentSession().saveOrUpdate(开发者_C百科dealer);
}


When you use saveOrUpdate the hibernate will save your data if the data with specific ID is not exists and It will update your data if the data with specific ID is exists


You might take a look at http://docs.jboss.org/hibernate/core/3.2/api/org/hibernate/engine/Cascade.html

Another approach is to check before saveOrUpdate


You will have to make a check for existing record before. There is no automatic way for Hibernate to figure out if a dealer record exists for a particular user and take a decision about save or update. I wish software could think :-)

Hope that helps.


Almost all my entities contains Identity field like Long id. so, my save() method looks like this:

void save(EntityWithId entity) {
    if (entity == null)
        return;
    if (entity.getId() == null) {
        session.persist(entity);
    } else {
        session.merge(entity);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜