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


你可能感兴趣的:(sql,Hibernate,mysql,HQL)