hibernate增刪改查的幾種方法
一.hql語句
1.增加語句:
(1) 原生session:
String hql = "FROM User u WHERE u.username = '"+username+"' AND u.password = '"+password+"'";
Session Session = getHibernateTemplate().getSessionFactory().getCurrentSession();
Query query = Session.createQuery(hql);
List<User> list = query.list();
(2)繼承HibernateDaoSupport後:
String hql = "FROM User u WHERE u.username = '"+username+"' AND u.password = '"+password+"'";
List<User> list = (List<User>) getHibernateTemplate().find(hql);
if(list.isEmpty()){
return null;
}else{
return list.get(0);
}
2.修改語句
Session Session = getHibernateTemplate().getSessionFactory().getCurrentSession();
Query query = Session.createQuery(hql);
query.executeUpdate();
(2)使用hibernate對映檔案中定義query方法
//queryName時更新語句的名字
介面:
void executeUpdata(String queryName,Object ...objects);
實現方法:
public void executeUpdata(String queryName, Object... objects) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
//獲得被命名的Query
Query query = session.getNamedQuery("user.changePassword");
//為HQL賦值(object就是陣列物件)
int lenth = objects.length;
int i = 0 ;
String f = "1";
try {
for (Object object : objects) {
query.setParameter(i++, object);
}
query.executeUpdate();
} catch (Exception e) {
f="2";
}
try {
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
對映檔案:
<query name="user.changePassword">
UPDATE User SET password = ? WHERE id = ?
</query>