zoukankan      html  css  js  c++  java
  • HQL查询语句

    先来一个简单的示例

     1     /**
     2      * 根据姓名查询用户
     3      * @param name 姓名
     4      * @return 用户对象
     5      */
     6     public User getUserBynName(String name){
     7         User user = null;
     8         Session session = null;
     9         try {
    10             session = HibernateUtils.getSession();
    11             String hql = " FROM User as user WHERE user.name = :name ";
    12             Query query = session.createQuery(hql);
    13             query.setString("name",name);
    14             user = (User) query.uniqueResult();
    15         }finally {
    16             if (session != null){
    17                 session.close();
    18             }
    19         }
    20         return user;
    21     }
    11             String hql = " FROM User as user WHERE user.name = ?";
    12             Query query = session.createQuery(hql);
    13             query.setString(1,name);

    这样也行,但不推荐。注意,索引从1开始


     1     public List<User> getUsersByName(String name){
     2         List<User> users = null;
     3         Session session = null;
     4         try {
     5             session = HibernateUtils.getSession();
     6             /*这里查的是User对象,不是user表,支持多态*/
     7             String hql = " FROM User as user WHERE user.name LIKE :name ";
     8             Query query = session.createQuery(hql);
     9             query.setString("name",name+"%");
    10             users = query.list();
    11         }finally {
    12             if (session != null){
    13                 session.close();
    14             }
    15         }
    16         return users;
    17     }

    分页查询

     1     public List<User> getUsersByName(String name){
     2         List<User> users = null;
     3         Session session = null;
     4         try {
     5             session = HibernateUtils.getSession();
     6             /*这里查的是User对象,不是user表,支持多态*/
     7             String hql = " FROM User as user WHERE user.name LIKE :name ";
     8             Query query = session.createQuery(hql);
     9             query.setString("name",name+"%");
    10             query.setFirstResult(10);
    11             query.setMaxResults(5);
    12             users = query.list();
    13         }finally {
    14             if (session != null){
    15                 session.close();
    16             }
    17         }
    18         return users;
    19     }
  • 相关阅读:
    自动生成 serialVersionUID 的设置
    常见的HTTP状态码(HTTP Status Code)说明
    PowerDesigner 创建表格及导出SQL语句
    简历
    idea+Maven+SSM框架增删改查
    @Resource和@Autowired的区别
    SSM java.lang.NullPointerException
    多进程和多线程的优缺点(二)
    多进程和多线程的优缺点
    基于swoole扩展实现真正的PHP数据库连接池
  • 原文地址:https://www.cnblogs.com/sherrykid/p/4575751.html
Copyright © 2011-2022 走看看