2015-04-04 25 views
0

,比如我有這些「簡化」類:Hibernate的更新對象的最佳實踐

class Employer { 
    int employerId; 
    String name; 
    Department department; 
} 

class Department { 
    int id; 
    String name; 
} 

這是推薦的方法做在冬眠更新(更換僱主的部門)

做的(對象的方法)

Employer e = employerDao.getById(id); 
e.setDepartment(new Department(newIdDept)); 
dao.save(e) 

或寫等(SQL方式)一個更新HQL DAO功能:

update set idDepartment=:newId where employerId=:id 

,並將它們,只需撥打dao.updateDepartment(employerId, newDptId);

回答

0

您應該使用SaveOrUpdate()方法。此方法在需要時調用save()update()。如果數據存在於數據庫中,則執行更新查詢。

+0

使用'saveOrUpdate'而不是'save'有什麼好處?猜測會影響索引插入,分區,觸發器以及性能;那是對的嗎? – beresfordt 2015-04-04 18:59:38