• 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     }
  • 相关阅读:
    探究 encode 和 decode 的使用问题(Python)
    C语言结构体在内存中的存储情况探究------内存对齐
    文件基本操作 (C语言)
    利用Xamaria构建Android应用-公交发车信息屏
    ChakraCore ,Net托管编程
    Go并发与.Net TAP
    码农视角
    让isis支持高德地图
    Fedora Server 上配置 MariaDb 集群
    .Net Sokcet 异步编程
  • 原文地址:https://www.cnblogs.com/sherrykid/p/4575751.html
Copyright © 2020-2023  润新知