当前位置:首页 > 开发 > 编程语言 > Hibernate > 正文

hibernate HQL的简单使用一

发表于: 2013-04-26   作者:chinrui   来源:转载   浏览次数:
摘要: Hibernate中的HQL使用 1、 建立相应的关系表 Category类: package com.edu.hpu; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class C
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();
	}
}


hibernate HQL的简单使用一

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
一、Hibernate提供的查询方式 OID查询方式:主键查询。通过get()或者load()方法加载指定OID的对象查
hibernate运行过程: Hibernate作用 1、hibernate是java应用和关系数据库之间的桥梁,她负责java对
在Aciton中直接进行数据库的操作。 --删除HibernateUtils.deleteAll(this.contentLogicInterface.ge
通过对Hibernate框架的学习,已经慢慢的对Hibernate有了进一步的了解,接下来我们要说的是Hibernate Q
DDL操作:增删改数据库表和数据库(hive中ddl操作是可以操作数据库的) DML操作:增删改数据 HIVE中特
一、数据库的emp名和dept表 建立持久化类和配置文件,可以用MyEclipse直接生成 持久化类 package en
有一次遇到需要在hql语句里用到in了,上一次查了半天也没搞定,最后索性用and、and、and代替了,但
from TCdiDrug t left join t.TCdiSupplier t1 where t.activeFlag='Y' 值得注意的几点: 1. 与sql
简介 SQL Server Reporting Services(SSRS),微软企业级报表平台,和SQL Server Integration Service
Hibernate是一种ORM(Object/Relation Mapping),对象关系映射,Hibernate的配置依赖于外部 XML 文
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号