Hibernate 标准API查询示例分享

Java-框架王 Hibernate 发布时间:2021-07-14 16:35:57 阅读数:15720 1
下文将使用一个标准查询操作讲述Hibernate的使用,如下所示: Hibernate Session接口提供了createCriteria() 方法,此方法可用于创建Criteria对象, 此方法可返回一个持久化对象的类的实例。 例:
Criteria cr = session.createCriteria(User.class);  
list results = cr.list();  

设置限定条件的标准查询,如:查询salary等于88的用户信息
Criteria cr = session.createCriteria(User.class);    
cr.add(Restrictions.eq("salary", 88));    
List results = cr.list();  


---下例为不同的条件组合 

Criteria cr = session.createCriteria(User.class);

// To get records having salary more than 88
cr.add(Restrictions.gt("salary", 88));

// To get records having salary less than 88
cr.add(Restrictions.lt("salary", 88));

// To get records having name starting with zhangsan
cr.add(Restrictions.like("name", "zhangsan%"));

// Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("name", "zhangsan%"));

// To get records having salary in between 88 and 1000
cr.add(Restrictions.between("salary", 88, 1000));

// To check if the given property is null
cr.add(Restrictions.isNull("salary"));

// To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"));

// To check if the given property is empty
cr.add(Restrictions.isEmpty("salary"));

// To check if the given property is not empty
cr.add(Restrictions.isNotEmpty("salary"));

---我们也可以模拟出逻辑表达式创建 AND 或 OR 的条件组合:

Criteria cr = session.createCriteria(User.class);

Criterion salary = Restrictions.gt("salary", 88);
Criterion name = Restrictions.ilike("firstNname","zhangsan%");

// To get records matching with OR condistions
LogicalExpression orExp = Restrictions.or(salary, name);
cr.add( orExp );

// To get records matching with AND condistions
LogicalExpression andExp = Restrictions.and(salary, name);
cr.add( andExp );

List results = cr.list();

分页使用标准接口
Criteria cr = session.createCriteria(User.class);
cr.setFirstResult(1);
cr.setMaxResults(10);
List results = cr.list();
排序结果 标准 API 提供了 org.hibernate.criterion.order 类可以去根据你的一个对象的属性把你的排序结果集按升序或降序排列。这个例子演示了如何使用 Order 类对结果集进行排序:
Criteria cr = session.createCriteria(User.class);
// To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));

// To sort records in descening order
crit.addOrder(Order.desc("salary"));

// To sort records in ascending order
crit.addOrder(Order.asc("salary"));

List results = cr.list();  

聚合API 标准 API 提供了 org.hibernate.criterion.projections 类可得到各属性值的平均值,最大值或最小值。 例:
Criteria cr = session.createCriteria(User.class);

// To get total row count.
cr.setProjection(Projections.rowCount());

// To get average of a property.
cr.setProjection(Projections.avg("salary"));

// To get distinct count of a property.
cr.setProjection(Projections.countDistinct("firstName"));

// To get maximum of a property.
cr.setProjection(Projections.max("salary"));

// To get minimum of a property.
cr.setProjection(Projections.min("salary"));

// To get sum of a property.
cr.setProjection(Projections.sum("salary"));  

标准查询示例
public class User {
   private int id;
   private String name;   
   private int salary;  

   public User() {}
   public User(String name,   int salary) {
      this.name = name; 
      this.salary = salary;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName( String name ) {
      this.name = name;
   }
    
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

database中的table
create table TbUser (
   id INT NOT NULL auto_increment,
    name VARCHAR(20) default NULL, 
   salary     INT  default NULL,
   PRIMARY KEY (id)
);
映射文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="User" table="TbUser">
      <meta attribute="class-description">
         This class contains the User detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="name" column="name" type="string"/> 
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping> 
main()方法中采用Criteria 进行查询


import java.util.List; 
import java.util.Date;
import java.util.Iterator; 

import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Projections;
import org.hibernate.cfg.Configuration;

public class ManageUser {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageUser  ME = new ManageUser();

      /* Add few user records in database */
      Integer id1 = ME.addUser("zhangsan", 2000);
      Integer id2 = ME.addUser("lisi",  5000);
      Integer id3 = ME.addUser("mazi", 5000);
      Integer id4 = ME.addUser("wanger", 3000);

      /* List down all the user */
      ME.listUsers();

      /* Print Total user's count */
      ME.countUser();

      /* Print Toatl salary */
      ME.totalSalary();
   }
   /* Method to CREATE an user in the database */
   public Integer addUser(String name,int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer userId = null;
      try{
         tx = session.beginTransaction();
         User user = new User(name, salary);
         userId = (Integer) session.save(user); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return userId;
   }

   /* Method to  READ all the user  having salary usersore than 2000 */
   public void listUsers( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Criteria cr = session.createCriteria(User.class);
         // Add restriction.
         cr.add(Restrictions.gt("salary", 2000));
         List users = cr.list();

         for (Iterator iterator = 
                           users.iterator(); iterator.hasNext();){
            User user = (User) iterator.next(); 
            System.out.print("Name: " + user.getName());  
            System.out.println("  Salary: " + user.getSalary()); 
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to print total number of records */
   public void countUser(){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Criteria cr = session.createCriteria(User.class);

         // To get total row count.
         cr.setProjection(Projections.rowCount());
         List rowCount = cr.list();

         System.out.println("Total Coint: " + rowCount.get(0) );
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
  /* Method to print sum of salaries */
   public void totalSalary(){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Criteria cr = session.createCriteria(User.class);

         // To get total salary.
         cr.setProjection(Projections.sum("salary"));
         List totalSalary = cr.list();

         System.out.println("Total Salary: " + totalSalary.get(0) );
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
}  

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Hibernate/202107/493.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者