天天看點

HQL查詢-分頁-條件-連接配接-過濾使用

大家好,又見面了,我是你們的朋友全棧君。

HQL(Hibernate Query Language)是hibernate自帶的查詢語言,進行了面向對象的分裝,今天就來學習一下,

建立一個java項目,結構如下:

HQL查詢-分頁-條件-連接配接-過濾使用

jar包和hibernate官網使用,參見《Hibernate環境搭建和配置》

實體類Book代碼:

package com.myeclipse.pojo;

import java.util.Date;
public class Book {
	
	private int id;
	private String author;
	private String name;
	private double price;
	private Date pubDate;
	private Category category;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Date getPubDate() {
		return pubDate;
	}
	public void setPubDate(Date pubDate) {
		this.pubDate = pubDate;
	}
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", author=" + author + ", name=" + name
				+ ", price=" + price + ", pubDate=" + pubDate + "]";
	}
	
	
}           

複制

Book.hbm.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.myeclipse.pojo">
	<class name="Book" table="t_book">
		<id name="id">
			<generator class="identity" />
		</id>
		<many-to-one name="category" class="Category" column="category_id" />
		<property name="author" />
		<property name="name" column="book_name" />
		<property name="price" />
		<property name="pubDate" />
		<!-- 使用過濾器 -->
		<filter name="bookFilter" condition="id=:id"></filter>

	</class>
	<!-- 過濾器定義 : 定義參數 -->
	<filter-def name="bookFilter">
		<filter-param name="id" type="integer" />
	</filter-def>

</hibernate-mapping>           

複制

Category實體類代碼:

package com.myeclipse.pojo;

import java.util.HashSet;
import java.util.Set;

public class Category{
	
	private int id;
	private String name;
	private Set<Book> books = new HashSet<Book>();

	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 Set<Book> getBooks() {
		return books;
	}
	public void setBooks(Set<Book> books) {
		this.books = books;
	}

}           

複制

Category.hbm.xml代碼如下:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
	
	
<hibernate-mapping package="com.myeclipse.pojo">
	<class name="Category" >
		<id name="id" >
			<generator class="identity" />
		</id>
		<property name="name" />
		<set name="books" inverse="true">
			<key>
				<column name="category_id" />
			</key>
			<one-to-many class="Book" />
		</set>
	</class>

</hibernate-mapping>           

複制

hibernate.cfg.xml代碼:

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
	<!-- 配置資料庫連接配接資訊 -->
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="connection.url">jdbc:mysql:///hibernate4</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<!-- 資料庫方言 -->
	<property name="hibernate.dialect">
		org.hibernate.dialect.MySQL5Dialect
	</property>
	<!-- 是否列印sql語句 -->
	<property name="show_sql">true</property>
	<!-- 格式化sql語句 -->
	<property name="format_sql">true</property>
	<!-- 資料庫更新方式: 
		1、create:每次更新都先把原有資料庫表删除,然後建立該表;
		2、create-drop:使用create-drop時,在顯示關閉SessionFacroty時(sessionFactory.close()),将drop掉資料庫Schema(表) 
		3、validate:檢測;
		4、update(常用):如果表不存在則建立,如果存在就不建立
	-->
	<property name="hbm2ddl.auto">update</property>
	<!-- hbm映射檔案 -->
	<mapping resource="com/myeclipse/pojo/Book.hbm.xml"/>
	<mapping resource="com/myeclipse/pojo/Category.hbm.xml"/>

</session-factory>
</hibernate-configuration>           

複制

HibernateUtil代碼:

package com.robert.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 * hibernate工具類
 */
public class HibernateUtil {

	private static Configuration cfg = null;
	private static SessionFactory factory = null;
	private static Session session = null ;
	
	static {
		init();
	}

	/**
	 * 初始化獲得Configuration和SessionFacroty對象
	 */
	public static void init() {
		cfg = new Configuration().configure();
		factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
				.applySettings(cfg.getProperties()).build());
	}

	/**
	 * 獲得Session對象
	 * @return
	 */
	public static Session getSession() {
		if (factory != null){
			return session = factory.openSession();
		}
		

		init();
		return session = factory.openSession();
	}
	
	/**
	 * 關閉Session
	 */
	public static void closeSession() {
		if(session!=null && session.isOpen())
			session.close();
	}

}           

複制

HibernateTest測試類代碼,包含建立資料庫表,儲存資料,查詢

package com.ghibernate.test;

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import com.myeclipse.pojo.Book;
import com.myeclipse.pojo.Category;
import com.robert.util.HibernateUtil;

public class HibernateTest {

	@Test
	public void testCreateDB() {
		Configuration cfg = new Configuration().configure();
		SchemaExport se = new SchemaExport(cfg);
		// 第一個參數:是否生成ddl腳本
		// 第二個參數:是否執行到資料庫中
		se.create(true, true);
	}

	@Test
	public void testSave() {

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		Category category = new Category();
		category.setName("文學");
		Category category1 = new Category();
		category1.setName("曆史");
		Category category2 = new Category();
		category2.setName("仙俠");
		Category category3 = new Category();
		category3.setName("科幻");
		Category category4 = new Category();
		category4.setName("恐怖");

		Book book = new Book();
		book.setName("讀者");
		book.setPrice(5.6);
		book.setAuthor("衆人");
		book.setPubDate(new Date());
		book.setCategory(category);

		Book book1 = new Book();
		book1.setName("傲慢與偏見");
		book1.setPrice(80.0);
		book1.setAuthor("簡.奧斯汀");
		book1.setPubDate(new Date());
		book1.setCategory(category1);

		Book book2 = new Book();
		book2.setName("中國曆史");
		book2.setPrice(30.0);
		book2.setAuthor("人民出版社");
		book2.setPubDate(new Date());
		book2.setCategory(category1);

		Book book3 = new Book();
		book3.setName("翩眇之旅");
		book3.setPrice(70.0);
		book3.setAuthor("蕭鼎");
		book3.setPubDate(new Date());
		book3.setCategory(category2);

		Book book4 = new Book();
		book4.setName("藍血人");
		book4.setPrice(60.0);
		book4.setAuthor("衛斯理");
		book4.setPubDate(new Date());
		book4.setCategory(category3);

		Book book5 = new Book();
		book5.setName("我的大學");
		book5.setPrice(60.5);
		book5.setAuthor("高爾基");
		book5.setPubDate(new Date());
		book5.setCategory(category);

		session.save(book);
		session.save(book1);
		session.save(book2);
		session.save(book3);
		session.save(book4);
		session.save(book5);
		session.save(category4);

		tx.commit();
		HibernateUtil.closeSession();

	}

	@Test
	public void testGet() {

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		Book book = (Book) session.get(Book.class, 1);
		System.out.println("book_name=" + book.getName() + "-----category="
				+ book.getCategory().getName());

		tx.commit();
		HibernateUtil.closeSession();

	}

	/**
	 * 查詢所有書名
	 */
	@Test
	public void testQuery() {
		Session session = HibernateUtil.getSession();
		String hql = "select name from Book";
		Query query = session.createQuery(hql);
		List<String> list = query.list();
		for (String bookname : list) {
			System.out.println(bookname);
		}

	}

	/**
	 * 查詢傳回多個列
	 */
	@Test
	public void testQueryMoreElements() {
		Session session = HibernateUtil.getSession();
		String hql = "select name, price from Book";
		Query query = session.createQuery(hql);
		// 查詢多個列時,傳回結果是數組集合,數組中元素的類型是有查詢列來決定的
		List<Object[]> list = query.list();
		for (Object[] objs : list) {
			System.out.println(objs[0] + "--------" + objs[1]);
		}

	}

	/**
	 * 查詢傳回對象
	 */
	@Test
	public void testQueryObject() {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		String hql = "select new Book(name, price) from Book";
		Query query = session.createQuery(hql);
		// 查詢多個列時,傳回結果是數組集合,數組中元素的類型是有查詢列來決定的
		List<Book> list = query.list();
		for (Book book : list) {
			System.out.println(book);
		}
		tx.commit();
		HibernateUtil.closeSession();

	}

	/**
	 * 查詢所有列
	 */
	@Test
	public void testQueryAll() {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		String hql = " from Book";
		Query query = session.createQuery(hql);
		List<Book> list = query.list();
		for (Book book : list) {
			System.out.println(book);
		}
		tx.commit();
		HibernateUtil.closeSession();

	}

	/**
	 * 條件查詢:使用占位符,從0開始
	 */
	@Test
	public void testQueryWhereConfition() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			String hql = " from Book where id < ? or price < ?";
			// String hql = " from Book where id < ? and price < ?" ;
			// setInteger:第一個參數是0表示第一個從占位符,第二個參數表示第一個占位符的值
			// setDouble:第一個參數是1,表示第二個占位符,第二個參數表示第二個占位符的值
			Query query = session.createQuery(hql).setInteger(0, 4)
					.setDouble(1, 400);
			;
			List<Book> list = query.list();
			for (Book book : list) {
				System.out.println(book);
			}
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 條件查詢:使用占位符,從0開始
	 */
	@Test
	public void testQueryWhereSetParameter() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			String hql = " from Book where id < ? ";
			// setParameter不用管參數的類型
			Query query = session.createQuery(hql).setParameter(0, 4);
			List<Book> list = query.list();
			for (Book book : list) {
				System.out.println(book);
			}
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 條件查詢之命名查詢,以冒号開頭,後跟名稱,在setParameter時,将該名稱放進去即可
	 */
	@Test
	public void testQueryWhereSetName() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			String hql = " from Book where id <:id ";
			// setParameter不用管參數的類型
			Query query = session.createQuery(hql).setParameter("id", 4);
			List<Book> list = query.list();
			for (Book book : list) {
				System.out.println(book);
			}
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 分頁查詢
	 */
	@Test
	public void testQueryPaging() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			String hql = " from Book ";
			// setFirstResults:資料從第幾個開始顯示(currentPage-1)*PageSize
			// setMaxResults:每頁顯示的資料數量PageSize
			Query query = session.createQuery(hql).setFirstResult(3)
					.setMaxResults(3);
			List<Book> list = query.list();
			for (Book book : list) {
				System.out.println(book);
			}
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 聚合函數----統計查詢
	 * 結果唯一
	 */
	@Test
	public void testQueryStatistics() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			String hql = " select count(b.name) from Book b ";
			Object count = session.createQuery(hql).uniqueResult() ;
			System.out.println("總數:"+count);
			
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	/**
	 * 分組查詢
	 */
	@Test
	public void testQueryGroupBy() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			String hql = " select b.category.name  , count(b.id) from Book b group by b.category.name ";
			List<Object[]> list = session.createQuery(hql).list() ;
			for (Object[] objs : list) {
				System.out.println(objs[0]+"---"+objs[1]);
			}
			
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * 排序查詢
	 */
	@Test
	public void testQueryOrderby() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			String hql = " from Book b Order by b.price desc ";
			List<Book> list = session.createQuery(hql).list() ;
			for (Book book : list) {
				System.out.println(book);
			}
			
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 對象導航
	 */
	@Test
	public void testQueryNavigation() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			//查詢“仙俠”類的書籍資訊
			String hql = " from Book b where b.category.name =:name  ";
			hql = " select b from Book b join b.category c where c.name =:name" ;
			hql = " select b from Book b inner join b.category c where c.name =:name" ;
			
			List<Book> list = session.createQuery(hql).setString("name", "仙俠").list() ;
			for (Book book : list) {
				System.out.println(book);
			}
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * 左外連接配接
	 */
	@Test
	public void testQueryLeftJoin() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			//查詢“仙俠”類的書籍資訊
			String hql = " select c.name , b.name from Category c left outer join c.books b ";
			List<Object[]> list = session.createQuery(hql).list() ;
			for (Object[] objs : list) {
				System.out.println(objs[0]+"---"+objs[1]);
			}
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * 過濾器的使用--過濾查詢--為查詢加上某些條件
	 * 過濾器的步驟:
	 * 1、定義過濾器;
	 * 2、使用過濾器-加條件;
	 * 3、查詢時,是過濾器生效
	 */
	@Test
	public void testQueryFilter() {
		try {
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			//啟用過濾器
			session.enableFilter("bookFilter").setParameter("id", 4) ;
			//查詢“仙俠”類的書籍資訊
			String hql = " from Book b ";
			List<Book> list = session.createQuery(hql).list() ;
			for (Book book : list) {
				System.out.println(book);
			}
			tx.commit();
			HibernateUtil.closeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
}           

複制

具體的結果自己運作一下就可以了。

釋出者:全棧程式員棧長,轉載請注明出處:https://javaforall.cn/151230.html原文連結:https://javaforall.cn