sql和hql的区别

转自:https://blog.csdn.net/lxf512666/article/details/52820368

hql是面向对象查询,格式:from + 类名 + 类对象 + where + 对象的属性

sql是面向数据库表查询,格式:from + 表名 + where + 表中字段

在hibernate中使用原生sql查询

例如:

public User login(User user) throws Exception {
    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 void modifyUserById(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) 

 

posted @ 2018-09-16 23:35  习惯沉淀  阅读(3635)  评论(0编辑  收藏  举报