`
chinrui
  • 浏览: 98028 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

hibernate HQL的简单使用一

阅读更多
Hibernate中的HQL使用
1、 建立相应的关系表
Category类:
package com.edu.hpu;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Category {

	private int id;
	private String name;
	
	@Id
	@GeneratedValue
	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;
	}
}

Topic类:
package com.edu.hpu;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class Topic {

	private int id;
	private String title;
	private Date date;
	private Category category;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="category_ID")
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
}

Msg类:
package com.edu.hpu;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class Msg {

	private int id;
	private String cont;
	private Topic topic;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCont() {
		return cont;
	}
	public void setCont(String cont) {
		this.cont = cont;
	}
	
	@ManyToOne
	@JoinColumn(name="topic_ID")
	public Topic getTopic() {
		return topic;
	}
	public void setTopic(Topic topic) {
		this.topic = topic;
	}
}

第12个查询用到的MsgInfo类:
package com.edu.hpu;

public class MsgInfo {

	private int id;
	private String cont;
	private String topicName;
	private String categoryName;
	
	public MsgInfo(int id, String cont, String topicName, String categoryName) {
		super();
		this.id = id;
		this.cont = cont;
		this.topicName = topicName;
		this.categoryName = categoryName;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCont() {
		return cont;
	}
	public void setCont(String cont) {
		this.cont = cont;
	}
	public String getTopicName() {
		return topicName;
	}
	public void setTopicName(String topicName) {
		this.topicName = topicName;
	}
	public String getCategoryName() {
		return categoryName;
	}
	public void setCategoryName(String categoryName) {
		this.categoryName = categoryName;
	}
}

Hibernate.cfg.xml配置信息:
<?xml version='1.0' encoding='utf-8'?>
<!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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">r</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <property name="format_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <!--<property name="hbm2ddl.auto">update</property>-->

        <!--<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>-->
        
        <!--<mapping resource="com/edu/hpu/Husband.hbm.xml" />-->
        <!--
        <mapping resource="com/edu/hpu/Teacher.hbm.xml" />
        <mapping resource="com/edu/hpu/Student.hbm.xml" />
        -->
        <mapping class="com.edu.hpu.Category" />
        <mapping class="com.edu.hpu.Topic" />
        <mapping class="com.edu.hpu.Msg" />
        
        
    </session-factory>

</hibernate-configuration>

简单的HQL测试类:
package com.edu.hpu;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestClass {

	private static SessionFactory sf = null;
	
	@BeforeClass
	public static void beforeClass() {
		Configuration conf = new Configuration().configure();
		ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
		sf = conf.buildSessionFactory(sr);
	}
	
	@Test
	public void testExport() {
		new SchemaExport(new Configuration().configure()).create(true ,true);
	}
	
	@Test
	public void testSave() {
		Session session = sf.openSession();
		session.beginTransaction();
		
		for(int i = 0; i < 10; i++) {
			Category c = new Category();
			c.setName("c" + i);
			session.save(c);
		}
		
		for(int i = 0; i < 10; i++) {
			Category c = new Category();
			c.setId(1);
			Topic t = new Topic();
			t.setTitle("t" + i);
			t.setCategory(c);
			session.save(t);
		}
		
		for(int i = 0; i < 10; i++) {
			Topic t = new Topic();
			t.setId(1);
			Msg m = new Msg();
			m.setTopic(t);
			m.setCont("m" + i);
			session.save(m);
		}
		
		session.getTransaction().commit();
		session.close();
	}
	
	@Test
	public void testHQL_1() {
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("from Category");
		List<Category> categories = (List<Category>)query.list();
		for(Category category : categories) {
			System.out.println(category.getName());
		}
		session.getTransaction().commit();
	}
	
	@Test
	public void testHQL_2() {
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("from Category c where c.name > 'c5'");
		List<Category> categories = (List<Category>)query.list();
		for(Category c : categories) {
			System.out.println(c.getName());
		}
		session.getTransaction().commit();
	}
	
	@Test
	public void testHQL_3() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query query = s.createQuery("from Category c order by c.name desc");
		List<Category> cs = query.list();
		for(Category c : cs) {
			System.out.println(c.getName());
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_4() {
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		Query q = session.createQuery("select distinct c from Category c order by c.name desc");
		List<Category> cs = (List<Category>)q.list();
		for(Category c : cs) {
			System.out.println(c.getName());
		}
		session.getTransaction().commit();
	}
	
	@Test
	public void testHQL_5() {
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		Query q = session.createQuery("from Category c where c.id > :min and c.id < :max");
		/*q.setParameter("min", 2);
		q.setParameter("max", 8);*/
		q.setInteger("min", 2);
		q.setInteger("max", 8);
		List<Category> cs = (List<Category>)q.list();
		for(Category c : cs) {
			System.out.println(c.getId() + "-" + c.getName());
		}
		session.getTransaction().commit();
	}
	
	@Test
	public void testHQL_6() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Category c where c.id > ? and c.id < ?")
				   .setInteger(0, 2).setInteger(1, 8);
		List<Category> cs = (List<Category>)q.list();
		for(Category c : cs) {
			System.out.println(c.getId() + " - " + c.getName());
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_7() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Category c order by c.id desc");
		q.setMaxResults(4);
		q.setFirstResult(0);
		List<Category> cs = (List<Category>)q.list();
		for(Category c : cs) {
			System.out.println(c.getId() + " - " + c.getName());
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_8() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("select c.id , c.name from Category c order by c.id desc");
		List<Object[]> cs = (List<Object[]>)q.list();
		for(Object[] c : cs) {
			System.out.println(c[0] + " - " + c[1]);
		}
		s.getTransaction().commit();
	}
	
	//把Topic的FetchType调成LAZY的时候,没有有第二条查询语句
	@Test
	public void testHQL_9() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Topic t where t.category.id = 1");
		List<Topic> ts = (List<Topic>)q.list();
		for(Topic t : ts) {
			System.out.println(t.getId());
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_10() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Topic t where t.category.id = 1");
		List<Topic> ts = (List<Topic>)q.list();
		for(Topic t : ts) {
			System.out.println(t.getId() + " = " + t.getCategory().getName());
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_11() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Msg m where m.topic.category.id = 1");
		List<Msg> ms = (List<Msg>)q.list();
		for(Msg m : ms) {
			System.out.println(m.getCont());
		}
		s.getTransaction().commit();
	}
	
	//VO Value Object
	//DTO Data Transfer Object
	@Test
	public void testHQL_12() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("select new com.edu.hpu.MsgInfo(m.id , m.cont, m.topic.title , m.topic.category.name) from Msg m");
		List<MsgInfo> ms = (List<MsgInfo>)q.list();
		for(MsgInfo m : ms ) {
			System.out.println(m.getCont() + " = " + m.getTopicName() + " = " + m.getCategoryName());
		}
		s.getTransaction().commit();
	}
	
	//必须写成t.category,必须指定使用哪个变量做的连接
	@Test
	public void testHQL_13() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("select t.title , c.name from Topic t join t.category c");
		List<Object[]> cs = (List<Object[]>)q.list();
		for(Object[] c : cs) {
			System.out.println(c[0] + " = " + c[1]);
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_14() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Category c where c = :CInfo");
		Category c = new Category();
		c.setId(1);
		q.setParameter("CInfo", c);
		
		Category cs = (Category)q.uniqueResult();
		System.out.println(cs.getName());
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_15() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("select count(*) from Category");
		long count = (Long)q.uniqueResult();
		System.out.println(count);
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_16() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Category c where c.id between 3 and 5");
		List<Category> cs = (List<Category>)q.list();
		for(Category c : cs) {
			System.out.println(c.getId() + " - " + c.getName());
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_17() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Category c where c.id in (1,3,5)");
		List<Category> cs = (List<Category>)q.list();
		for(Category c : cs) {
			System.out.println(c.getId() + " - " + c.getName());
		}
		s.getTransaction().commit();
	}
	
	@Test
	public void testHQL_18() {
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from Msg m where m.cont is not null");
		List<Msg> cs = (List<Msg>)q.list();
		for(Msg c : cs) {
			System.out.println(c.getId() + " - " + c.getCont());
		}
		s.getTransaction().commit();
	}
	
	@AfterClass
	public static void afterClass() {
		sf.close();
	}
}


分享到:
评论

相关推荐

    hibernateHQL关联查询

    其中,HQL(Hibernate Query Language)作为Hibernate提供的查询语言之一,允许开发者以接近面向对象的方式编写查询语句。本文将重点介绍Hibernate中的关联查询,并深入探讨HQL关联查询的实现原理及应用场景。 ####...

    Hibernate hql查询语法总结

    其内置的HQL(Hibernate Query Language)是一种面向对象的查询语言,它允许开发者以类和对象的方式进行数据查询。本文将对Hibernate HQL查询语法进行总结,涵盖基础查询、属性查询、实例化查询以及查询链接等多个...

    Hibernate-HQL.rar_HQL_hibernate hql

    本篇文档将深入探讨Hibernate中的HQL(Hibernate Query Language),一种面向对象的查询语言,它提供了与SQL类似的语法,但更贴近于面向对象的思维模式,使得开发者可以更加便捷地进行数据查询。 一、HQL简介 HQL是...

    Hibernate HQL.txt

    下面是一个简单的Java程序示例,展示了如何在Java中使用Hibernate框架执行HQL查询: ```java import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate....

    Hibernate HQL 结合 velocity

    **Hibernate HQL(Hibernate Query Language)** 是Hibernate提供的一个面向对象的查询语言,类似于SQL,但它是针对对象模型设计的。HQL允许开发者使用类和属性的名字而不是表和列名进行查询,从而降低了对底层...

    hibernate hql基本操作

    HQL,即Hibernate Query Language,是Hibernate提供的一种强大的查询语言。虽然它的语法结构看起来与SQL类似,但其实质上是一种面向对象的语言,能够理解并处理诸如继承、多态及关联等概念。 #### 二、HQL的基本...

    hibernate hql各类查询范例

    以上内容涉及了使用 HQL 和 DetachedCriteria 进行查询、参数化查询、执行更新操作以及简单的统计查询等常见的 Hibernate 操作。这些知识点对于理解和掌握 Hibernate 框架的基本使用至关重要,同时也是开发基于 ...

    Hibernate HQL查询 分页查询 模糊查询.docx

    HQL(Hibernate Query Language)是一种面向对象的查询语言,它允许开发者使用类及其属性来编写查询语句,而不是传统的SQL语句。这使得开发人员能够更加专注于业务逻辑而不用深入到SQL层面。HQL支持各种复杂的查询,...

    Hibernate HQL查询.docx

    以上代码展示了如何使用 HQL 进行一个简单的查询,其结果为 User 实体的列表。 #### 四、HQL 查询类型 根据返回类型的不同,HQL 查询可以分为以下几种: 1. **单个对象** - 当查询结果预期为单个对象时,可以使用...

    Hibernate HQL精华

    总结,Hibernate HQL是Java开发者处理数据库查询的强大工具,它提供了一种面向对象的方式来表达SQL查询,使代码更加可读且易于维护。通过理解并熟练掌握HQL,可以显著提高开发效率,更好地利用Hibernate框架的潜力。

    hibernate hql大全

    **Hibernate HQL 全攻略** Hibernate Query Language(HQL)是Hibernate框架提供的面向对象的查询语言,它允许开发者以类和属性的名称进行查询,而不是直接操作数据库的表和列。HQL的强大之处在于它将数据库操作与...

    HQL是hibernate自己的一套查询

    根据提供的标题、描述以及部分代码内容,我们可以了解到这段材料主要涉及的是Hibernate框架中的HQL(Hibernate Query Language)查询语言的使用。接下来将详细介绍HQL的相关知识点。 ### HQL概述 HQL是Hibernate...

    hibernate hql语句

    HQL是一种专门为Hibernate设计的查询语言,其语法结构接近于标准SQL,但又具有面向对象的特性。HQL允许开发者以一种更为简洁、直观的方式进行数据库查询操作。与Criteria API相比,HQL提供更丰富的特性和灵活性。 #...

    Hibernate之HQL查询

    例如,假设我们有一个`Student`类,包含`name`和`age`属性,一个简单的HQL查询可能如下: ```sql SELECT s FROM Student s WHERE s.age &gt; 18 ``` 这个查询会返回所有年龄大于18岁的学生对象。 **2. HQL的SELECT...

    hibernate的HQL的模糊查询

    综上所述,Hibernate的HQL模糊查询是开发中不可或缺的工具,它提供了一种简单而强大的方式来处理数据库的模糊查询需求。通过理解并熟练掌握这些概念,可以更好地利用Hibernate进行数据操作,提升项目的开发效率和...

    Hibernate hql查询

    Hibernate Query Language(HQL)是Hibernate框架提供的一种面向对象的查询语言,它是基于Java的,但其语法与SQL类似,用于在Java应用中操作对象。HQL允许开发者用类名和属性名而不是表名和列名进行数据库查询,这...

    hibernate 查询?Hibernate的HQL查询

    【描述】:在ORM框架Hibernate中,数据查询和检索是一个核心功能,它提供了多种查询方式,包括标准化对象查询(Criteria Query)、Hibernate查询语言(HQL)和原生SQL查询。其中,HQL作为官方推荐的查询方式,具有...

    Hibernate教程(数据查询)HQL,PDF格式

    通过上述介绍,我们可以看到Hibernate和HQL的强大之处在于它们能够提供一种简单且直观的方式来处理数据库操作,特别是数据查询。对于那些希望在Java应用程序中集成数据库功能的开发者来说,掌握Hibernate和HQL是必不...

    HIBERNATE HQL

    HQL,即Hibernate Query Language,是Hibernate框架中的一种强大且灵活的查询语言。虽然它的语法看起来与SQL类似,但其实质上是一种面向对象的语言,能够很好地理解并处理对象模型中的概念,如继承、多态和关联等。...

Global site tag (gtag.js) - Google Analytics