HQL查询-分页-条件-连接-过滤使用

HQL查询-分页-条件-连接-过滤使用HQL(HibernateQueryLanguage)是hibernate自带的查询语言,进行了面向对象的分装,今天就来学习一下,新建一个java项目,结构如下:jar包和hibernate官网使用,参见《Hibernate环境搭建和配置》实体类Book代码:packagecom.myeclipse.pojo;importjava.uti

大家好,又见面了,我是你们的朋友全栈君。

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();
		}

	}

	
}

具体的结果自己运行一下就可以了。







版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/151230.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Linux find命令根据时间筛选出文件进行删除

    Linux find命令根据时间筛选出文件进行删除

  • Ubuntu 使用Compiz配置炫酷3D桌面

    Ubuntu 使用Compiz配置炫酷3D桌面先看一下效果要实现这种3D的效果其实很简单.Step1:安装N卡驱动工具sudoapt-getinstallnvidia-331这个东西其实没有太大的作用.Step2:安装Compizsu

  • JavaScript清空数组的三种方法

    JavaScript清空数组的三种方法1、length用length方法可以很轻松地清空数组,代码示例:vararr=[1,2,3];console.log(arr);arr.length=0;console.log(arr);结果如下:2、splisesplice()方法向/从数组中添加/删除项目,然后返回被删除的项目vararr=[1,2,3]…

  • 三种方法遍历二叉树_java遍历arraylist

    三种方法遍历二叉树_java遍历arraylistArrayList的多种遍历方法

  • linux top命令 详解「建议收藏」

    linux top命令 详解「建议收藏」top命令主要用来观察和收集运行在系统上的进程的一些有用信息。ps只是一个快照,是ps命令执行的那一瞬间的系统中进程的快照。top则可以用于持续观察。第一步,在命令行键入top,回车进入top管理界面。第一行其实和uptime的执行效果是一样的。分析一下,12:48:06是当前运行这个命令的时候,机器的时间。up134days,19:36,指的是说这台机器,持续运行了134天了,启动于134天前的19:36。5users代表的是当前运行这个命令的时候,这台机器上总共登陆有5个用

  • 大数据:数据采集平台之Fluentd

    大数据:数据采集平台之Fluentd大数据:数据采集平台之Fluentd官网:http://docs.fluentd.org/articles/quickstartFluentd是一个开源的数据收集框架。Fluentd使用C/Ruby开发,使用JSON文件来统一日志数据。它的可插拔架构,支持各种不同种类和格式的数据源和数据输出。最后它也同时提供了高可靠和很好的扩展性。TreasureData,Inc对该产品提供支持和维…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号