hql是面向对象查询,格式:from + 类名 + 类对象 + where + 对象的属性
sql是面向数据库表查询,格式:from + 表名 + where + 表中字段
在hibernate中使用原生sql查询
例如:
public User login(User user) throwsException {
String sql= "select id,name,password,phone,address,email,regDate"
+ " from user as u where u.name = ? and u.password = ?";
Session session=sessionFactory.openSession();
SQLQuery sqlQuery=session.createSQLQuery(sql);
sqlQuery.setString(0, user.getName());
sqlQuery.setString(1, user.getPassword());
sqlQuery.addEntity(User.class);
Object obj=sqlQuery.uniqueResult();
session.close();if (obj == null)return null;return(User) obj;
}
在hibernate中使用hql查询
例如:
public voidmodifyUserById(User user) {
Session session=HibernateSessionFactory.getSession();
Transaction transaction=session.beginTransaction();
String hql= "update User as u set u.userName = ?
,u.passWord = ? ,u.sex = ? where u.id = ? ";
Query query=session.createQuery(hql);
query.setCacheable(false);
query.setString(0, user.getUserName());
query.setString(1, user.getPassWord());
query.setString(2, user.getSex());
query.setString(3, user.getId());
System.out.println("执行了啊" + user.getUserName() +user.getId());
query.executeUpdate();
transaction.commit();
session.flush();
session.close();
}
注意:在hibernate中占位符“?”填充参数下表从 0开始。
JDBC填充时占位符从1开始。
hibernate中给参数起别名方法填充
List users = session.createQuery(“select u.id, u.name
from User u where u.name
like :myname and u.id=:myid”).setParameter(“myname”, “%张%”).setParameter(“myid”, 1) .list();
定义命名参数固定格式: :+参数名称(即:myid ),赋值时,直接写参数名即可: setParameter(“myid”, 1)