1. 程式人生 > >hibernate的查詢方式及抓取策略

hibernate的查詢方式及抓取策略

查詢方式

      根據唯一標識id進行檢索:

                  get與load方法(https://blog.csdn.net/qq_40605913/article/details/81460410)。

      物件導航檢索:

                  根據一個已經查詢到的物件,獲得其關聯的物件。

     HQL查詢:

             Hibernate Query Language,Hibernate的查詢語言,是一種面向物件的方式的查詢語言,語法類似SQL。通過session.createQuery(),用於接收一個HQL進行查詢方式。

簡單查詢:

       //HQL的簡單查詢
	public void test(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		
		Query query = session.createQuery("from Customer");
		
		List<Customer> list = query.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		transaction.commit();
	}
      //HQL的簡單查詢之別名查詢
	public void test(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		//c是別名,但HQL不支援*,聚合函式中的*除外
		Query query = session.createQuery("select c from Customer c");
		
		List<Customer> list = query.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		transaction.commit();
	}

排序查詢:

      //HQL的排序查詢
	public void test3(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		//預設
//		Query query = session.createQuery(" from Customer order by cust_id");
		//降序
		Query query = session.createQuery(" from Customer order by cust_id desc");
		//升序
//		Query query = session.createQuery("  from Customer order by cust_id asc");

		List<Customer> list = query.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		transaction.commit();
	}

條件查詢:

     public void test3(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		
		//條件查詢
		//1.按位置繫結,多個條件時類推
//		Query query = session.createQuery("from Customer where cust_id=?");
//		query.setParameter(0, 1l);
//		List<Customer> list = query.list();
		//2.按名稱繫結--根據引數位置進行繫結
														//aaa,bbb這些名字隨便起,但與:之間不能有空格
		Query query = session.createQuery("from Customer where cust_id = :aaa and cust_name = :bbb");
		//設定引數
		query.setParameter("aaa", 1l);
		query.setParameter("bbb", "22");
		
		List<Customer> list = query.list();
		
		transaction.commit();
	}

投影查詢:

       public void test3(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		//單個屬性
//		List<Object> list = session.createQuery("select c.cust_name from Customer c").list();
		//多個屬性
//		List<Object []> list = session.createQuery("select c.cust_name,c.cust_id from Customer c").list();
		
//		for (Object [] object : list) {
//			System.out.println(Arrays.toString(object));
//		}
		//將查詢結果封裝到物件中
		List<Customer> list = session.createQuery("select new Customer(cust_name,cust_id) from Customer").list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		transaction.commit();
	}
	

分頁查詢:

      //HQL的分頁查詢
	public void test3(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();

		Query query = session.createQuery("from Customer");
		
		query.setFirstResult(0);
		query.setMaxResults(2);
		
		List<Customer> list = query.list();
		
		for (Object object : list) {
			System.out.println(object);
		}
		
		transaction.commit();
	}

分組統計查詢:

      //HQL的分組統計查詢
	public void test3(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();

		//聚合函式:count(),sum(),max(),min(),avg()
//		Object object = session.createQuery("select count(*) from Customer").uniqueResult();
//		System.out.println(object);
		
		Query query = session.createQuery("select cust_id,count(*) from Customer group by cust_name");
		List<Object[]> object = query.list();
		for (Object[] object2 : object) {
			System.out.println(Arrays.toString(object2));
		}
		transaction.commit();
	}

QBC:

 Query By Criteria,條件查詢。是一種更加面向物件化的查詢的方式。

簡單查詢:

	//簡單查詢
	public void test(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		
		//獲得Criteria物件
		Criteria criteria = session.createCriteria(Customer.class);
		List<Customer> list = criteria.list();
		for (Customer customer : list) {
			System.out.println(customer.toString());
		}
		transaction.commit();
	}

排序查詢:

          //排序查詢
		public void test1(){
			Session session = HibernateUtils.getCurrentSession();
			Transaction transaction = session.beginTransaction();
			
			//獲得Criteria物件
			Criteria criteria = session.createCriteria(Customer.class);
			//升序查詢,對應降序為desc
			criteria.addOrder(Order.asc("cust_id"));
			
			List<Customer> list = criteria.list();
			for (Customer customer : list) {
				System.out.println(customer.toString());
			}
			transaction.commit();
		}

分頁查詢:

          //分頁查詢
		public void test1(){
			Session session = HibernateUtils.getCurrentSession();
			Transaction transaction = session.beginTransaction();
			
			//獲得Criteria物件
			Criteria criteria = session.createCriteria(Customer.class);
			
			criteria.setFirstResult(0);
			criteria.setMaxResults(2);
			
			List<Customer> list = criteria.list();
			for (Customer customer : list) {
				System.out.println(customer);
			}
			transaction.commit();
		}

條件查詢:

          //條件查詢
		public void test1(){
			Session session = HibernateUtils.getCurrentSession();
			Transaction transaction = session.beginTransaction();
			
			//獲得Criteria物件
			Criteria criteria = session.createCriteria(Customer.class);
			
			/**
			 * =  eq
			 * >  gt
			 * >= ge
			 * <  lt
			 * <= le
			 * <> ne 不等於
			 */
			//設定條件
			criteria.add(Restrictions.eq("cust_name", "11"));
			
			List<Customer> list = criteria.list();
			for (Customer customer : list) {
				System.out.println(customer);
			}
			transaction.commit();
		}

統計查詢:

          //統計查詢
		@Test
		public void test1(){
			Session session = HibernateUtils.getCurrentSession();
			Transaction transaction = session.beginTransaction();
			
			//獲得Criteria物件
			Criteria criteria = session.createCriteria(Customer.class);
		
			/**
			 * add :普通的條件,where後面事件
			 * addOrder:排序
			 * setProjection:聚合函式和group by having
			 */
			criteria.setProjection(Projections.rowCount());
			Long num = (Long)criteria.uniqueResult();
			
			System.out.println(num);
			
			transaction.commit();
		}

離線查詢:

        //離線查詢
	public void test1(){
	
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);
		detachedCriteria.add(Restrictions.ilike("cust_name", "1%"));
		
		
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		
		Criteria  criteria = detachedCriteria.getExecutableCriteria(session);
		List<Customer> list = criteria.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
	}

多表查詢:

        //多表查詢
	public void test1(){	
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		//SQL:SELECT * FROM cst_customer c INNER JOIN cst_linkman l ON c.cust_id = l.lkm_cust_id;
		
		//HQL(內連線):from Customer c inner join c.linkMans
		//List<Object[]> list = session.createQuery("from Customer c inner join c.linkMans").list();
		
		//HQL(迫切內連線):在普通內連線inner join後新增一個關鍵字fetch。它發的SQL語句與
		//內連線一樣,作用:通知hibernate將資料封裝到物件裡,因為Customer中有LinkMan的集合,所以把
		//LinkMan封裝到Customer中,返回的list集合中放的是Customer(select distincr c 是為了去掉重複)
		List<Object[]> list = session.createQuery("select distinct c from Customer c inner join fetch c.linkMans").list();
		
	}

SQL:

        public void test1(){	
			Session session  = HibernateUtils.getCurrentSession();
			Transaction transaction = session.beginTransaction();
			
			SQLQuery sqlQuery = session.createSQLQuery("select * from cst_customer");
			
			sqlQuery.addEntity(Customer.class);
			
			List<Customer> list = sqlQuery.list();
			
			for (Customer customer : list) {
				System.out.println(customer);
			}
			
			transaction.commit();
		}			

延遲載入:

       延遲載入:lazy(懶載入)。執行到該行程式碼的時候,不會發送語句去進行查詢,在真正使用這個物件的屬性的時候才會傳送SQL語句進行查詢。

 類級別延遲載入:

    //類級別延遲載入,在<class>標籤上配置lazy=true,這樣load方法就和get方法一樣
	//在使用時才傳送查詢語句
	public void test1(){
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		
		session.load(Customer.class, 1l);
		
		transaction.commit();
	}

          讓lazy失效:

                        將lazy設定為false

                        持久化類使用final修飾

                         Hibernate. Initialize()

關聯級別:

        在<set>和<many-to-one>上來配置

抓取策略:

 

<set>上的fetch和lazy

             fetch:抓取策略,控制SQL語句格式

                             select                :預設值,傳送普通的select語句,查詢關聯物件

                             join                    :傳送一條迫切左外連線查詢關聯物件

                             subselect         :傳送一條子查詢查詢其關聯物件

             lazy:延遲載入,控制查詢關聯物件的時候是否採用延遲

                             true                   :預設值,查詢關聯物件的時候,採用延遲載入

                             false                  :查詢關聯物件的時候,不採用延遲載入

                             extra                 :及其懶惰。

<many-to-one>上的fetch和lazy

            fetch :抓取策略,控制SQL語句格式。

                             select       :預設值,傳送普通的select語句,查詢關聯物件。

                             join           :傳送一條迫切左外連線。

            lazy   :延遲載入,控制查詢關聯物件的時候是否採用延遲。

                             proxy        :預設值,proxy具體的取值,取決於另一端的<class>上的lazy的值。

                             false         :查詢關聯物件,不採用延遲。

                             no-proxy  :(不會使用)

批量抓取:

                 一批關聯物件一起抓取,batch-size

                 <set>上可以配置batch-size,但one-many中不能配置,需要在一的一方的class標籤中配置這個屬性