Hibernate 修改數(shù)據(jù)
1.用 HQL方式來更新
在 這里修改 Person 的name 和age 通過 id 標(biāo)識
Session currentSession = H3Utils.getCurrentSession();
currentSession.beginTransaction();
//創(chuàng)建 HQL
String hqlString = "update Person p set p.name=? , p.age=? where p.id=?";
//構(gòu)建 Query
Query query = currentSession.createQuery(hqlString);
//設(shè)置參數(shù)
query.setParameter(0, "小明");
query.setParameter(1, 18);
query.setParameter(2, 1);
//更新
query.executeUpdate();
currentSession.getTransaction().commit();
2 使用 HQL方式來更新
public void updateFunction2() {
Session currentSession = H3Utils.getCurrentSession();
currentSession.beginTransaction();
//創(chuàng)建SQL
String sql = "UPDATE t_person_list SET name='cv',age=2 WHERE id=4" ;
//執(zhí)行
currentSession.createSQLQuery(sql).executeUpdate();
//提交
currentSession.getTransaction().commit();
}
3 使用 OID方式來更新
Session currentSession = H3Utils.getCurrentSession();
currentSession.beginTransaction();
Person person = new Person();
person.setId(44);
person.setName("ccb");
person.setAge(90);
currentSession.update(person);
currentSession.getTransaction().commit();
- 使用 session.update()方法,根據(jù)主鍵去更新數(shù)據(jù),如果數(shù)據(jù)存在,那么就可以更新,如果不存在,拋異常報錯
- 可以使用 session.saveOrUpdate(person);方法,根據(jù)主鍵去更新數(shù)據(jù),如果數(shù)據(jù)存在,那么就可以更新,如果不存在,就執(zhí)行 insert
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
您可能感興趣的文章:- Hibernate迫切連接和普通連接的區(qū)別實例詳解
- hibernate通過session實現(xiàn)增刪改查操作實例解析
- 在已有spring的基礎(chǔ)上集成hibernate的實例講解
- hibernate屬性級別注解實例代碼
- JSP開發(fā)之hibernate之單向多對一關(guān)聯(lián)的實例
- hibernate4快速入門實例詳解
- Hibernate識別數(shù)據(jù)庫特有字段實例詳解
- Hibernate初體驗及簡單錯誤排除代碼詳解