`

栏目、帖子、回复(设置导航便于操作)HQL使用01

HQL 
阅读更多
栏目、帖子、回复(设置导航ManyToOne便于操作 HQL语句)01


[b]一、Category.java
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.java

import java.util.Date;

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

@Entity
public class Topic {
	private int id;
	private String title;
	private Category category;
	//private Category category2;
	
	private Date createDate;
	
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	@ManyToOne(fetch=FetchType.LAZY)
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.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;
	}
	
}


三、Msg.java

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

@Entity
public class Msg {
	private int id;
	private String cont;
	private Topic topic;
	@ManyToOne
	public Topic getTopic() {
		return topic;
	}
	public void setTopic(Topic topic) {
		this.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;
	}
	
}



四、MsgInfo.java

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


public class MsgInfo { //VO DTO Value Object 用户注册时,输入两个密码username p1 p2 UserInfo->User->DB
	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 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;
	}
	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;
	}
	
}



五、test

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

import org.hibernate.Query; 

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class HibernateQLTest {
	private static SessionFactory sf;
	
	@BeforeClass
	public static void beforeClass() {
		sf = new AnnotationConfiguration().configure().buildSessionFactory();
	}
	@AfterClass
	public static void afterClass() {
		sf.close();
	}
	
	@Test
	public void testSchemaExport() {
		new SchemaExport(new AnnotationConfiguration().configure()).create(false, 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.setCategory(c);
			t.setTitle("t" + i);
			t.setCreateDate(new Date());
			session.save(t);
			
		}
		
		for(int i=0; i<10; i++) {
			
			Topic t = new Topic();
			t.setId(1);
			Msg m = new Msg();
			m.setCont("m" + i);
			m.setTopic(t);
			session.save(m);
			
		}
		
		
		
		
		session.getTransaction().commit();
		session.close();
	}
	@Test
	public void testHQL_01() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Category");
		List<Category> categories = (List<Category>)q.list();
		for(Category c : categories) {
			System.out.println(c.getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_02() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Category c where c.name > 'c5'");
		List<Category> categories = (List<Category>)q.list();
		for(Category c : categories) {
			System.out.println(c.getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_03() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Category c order by c.name desc");
		List<Category> categories = (List<Category>)q.list();
		for(Category c : categories) {
			System.out.println(c.getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_04() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("select distinct c from Category c order by c.name desc");
		List<Category> categories = (List<Category>)q.list();
		for(Category c : categories) {
			System.out.println(c.getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_05() {
		Session session = sf.openSession();
		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);*/
		
		Query q = session.createQuery("from Category c where c.id > :min and c.id < :max")
			.setInteger("min", 2)
			.setInteger("max", 8);
		List<Category> categories = (List<Category>)q.list();
		for(Category c : categories) {
			System.out.println(c.getId() + "-" + c.getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_06() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Category c where c.id > ? and c.id < ?");
		q.setParameter(0, 2)
			.setParameter(1, 8);
//		q.setParameter(1, 8);
		List<Category> categories = (List<Category>)q.list();
		for(Category c : categories) {
			System.out.println(c.getId() + "-" + c.getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	//分页
	@Test
	public void testHQL_07() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Category c order by c.name desc");
		q.setMaxResults(4);
		q.setFirstResult(2);
		List<Category> categories = (List<Category>)q.list();
		for(Category c : categories) {
			System.out.println(c.getId() + "-" + c.getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_08() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("select c.id,  c.name from Category c order by c.name desc");
		List<Object[]> categories = (List<Object[]>)q.list();
		for(Object[] o : categories) {
			System.out.println(o[0] + "-" + o[1]);
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	//设定fetch type 为lazy后将不会有第二条sql语句
	@Test
	public void testHQL_09() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Topic t where t.category.id = 1");
		List<Topic> topics = (List<Topic>)q.list();
		for(Topic t : topics) {
			System.out.println(t.getTitle());
			//System.out.println(t.getCategory().getName());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	//设定fetch type 为lazy后将不会有第二条sql语句
	@Test
	public void testHQL_10() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Topic t where t.category.id = 1");
		List<Topic> topics = (List<Topic>)q.list();
		for(Topic t : topics) {
			System.out.println(t.getTitle());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_11() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Msg m where m.topic.category.id = 1");
		
		for(Object o : q.list()) {
			Msg m = (Msg)o;
			System.out.println(m.getCont());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	//了解即可
	//VO Value Object
	//DTO data transfer object
	@Test
	public void testHQL_12() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("select new com.bjsxt.hibernate.MsgInfo(m.id, m.cont, m.topic.title, m.topic.category.name) from Msg");
		
		for(Object o : q.list()) {
			MsgInfo m = (MsgInfo)o;
			System.out.println(m.getCont());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	//动手测试left right join
	//为什么不能直接写Category名,而必须写t.category
	//因为有可能存在多个成员变量(同一个类),需要指明用哪一个成员变量的连接条件来做连接
	@Test
	public void testHQL_13() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("select t.title, c.name from Topic t join t.category c "); //join Category c
		for(Object o : q.list()) {
			Object[] m = (Object[])o;
			System.out.println(m[0] + "-" + m[1]);
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	//学习使用uniqueResult
	@Test
	public void testHQL_14() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Msg m where m = :MsgToSearch "); //不重要
		Msg m = new Msg();
		m.setId(1);
		q.setParameter("MsgToSearch", m);
		
		Msg mResult = (Msg)q.uniqueResult();
		System.out.println(mResult.getCont());
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_15() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("select count(*) from Msg m");
		
		long count = (Long)q.uniqueResult();
		System.out.println(count);
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_16() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("select max(m.id), min(m.id), avg(m.id), sum(m.id) from Msg m");
		
		Object[] o = (Object[])q.uniqueResult();
		System.out.println(o[0] + "-" + o[1] + "-" + o[2] + "-" + o[3]);
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_17() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Msg m where m.id between 3 and 5");
		
		for(Object o : q.list()) {
			Msg m = (Msg)o;
			System.out.println(m.getId() + "-" + m.getCont());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	@Test
	public void testHQL_18() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Msg m where m.id in (3,4, 5)");
		
		for(Object o : q.list()) {
			Msg m = (Msg)o;
			System.out.println(m.getId() + "-" + m.getCont());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	//is null 与 is not null
	@Test
	public void testHQL_19() {
		Session session = sf.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from Msg m where m.cont is not null");
		
		for(Object o : q.list()) {
			Msg m = (Msg)o;
			System.out.println(m.getId() + "-" + m.getCont());
		}
		session.getTransaction().commit();
		session.close();
		
	}
	
	public static void main(String[] args) {
		beforeClass();
	}
}
分享到:
评论

相关推荐

    hql语句 使用大全

    ### HQL语句使用大全 HQL(Hibernate Query Language)是一种面向对象的查询语言,它提供了灵活而强大的数据检索方式,使开发人员能够更高效地与数据库交互。本文将详细介绍HQL的基本用法及高级特性。 #### 1. ...

    HQL的具体内容和使用

    Hibernate Query Language(HQL)是Hibernate框架中专用于对象关系映射(ORM)的查询语言,它使得开发者能够以面向对象的方式来查询...掌握HQL可以帮助我们在使用Hibernate进行ORM开发时更加高效地进行数据查询和操作。

    HQL语句 HQL语句

    HQL语句 HQL语句 HQL语句 HQL语句 HQL语句

    hql ppt Hql PPt

    Hql PPt Hql PPt

    HQL语法入门学习HQL语法入门学习

    这两个方法都遵循了上述的HQL使用步骤,通过`createQuery`创建Query对象,然后设置参数并执行查询。在`findPersonByHappenDate`中,还涉及到日期的解析和设置,这是在处理时间相关的查询时常见的做法。 总结来说,...

    HQL Eclipse Plugins 配置教程

    不喜欢使用myEclipse的...最近在项目中使用Hibernate,由于需要使用HQL,找了很多资料,大都是MyEclipse中自带的HQL工具。 由于MyEclipse是收费的,速度不是很理想。所以在网上找到了一个elipse插件 英文图文教程 ...

    精通HQL(word格式)

    4. **对象导航**:通过对象关系,HQL可以方便地进行关联查询,无需关心底层的表连接操作。 总之,HQL作为Hibernate的重要组成部分,为开发者提供了强大且灵活的数据检索能力,使得在Java应用中操作数据库变得更加...

    Hibernate查询语言HQL.PPT

    它提供了灵活多样的查询机制,包括导航对象图、通过标识符检索、使用 HQL 检索对象、使用 Hibernate 条件 API 和使用本地 SQL 查询等。 在 Hibernate 中检索对象的各种方法: 1. 导航对象图:通过对象的关联关系,...

    HQL查询及语法

    4. **设置参数**:如果HQL语句中包含参数,需调用Query对象的`setXxx`方法为其赋值。 5. **执行查询并处理结果**:最后,通过调用Query对象的`list`等方法,获取查询结果并进行后续处理。 #### 三、HQL语法示例...

    HQL语句大全HQL语句大全

    ### HQL语句详解 #### 一、HQL简介 HQL(Hibernate Query Language)是Hibernate框架中的查询语言,它提供了面向对象的方式来进行数据库...在实际开发中,合理利用HQL可以极大地提高数据库操作的效率和代码的可读性。

    hql分页

    HQL是Hibernate框架提供的面向对象的查询语言,它类似于SQL,但直接操作对象和类,而不是数据库表。在处理大数据量的查询时,分页查询显得尤为重要,因为它避免一次性加载所有数据导致内存溢出和性能下降。 1. **...

    全面解析HQL语句 非常详细直接的HQL语句的功能介绍

    标题:“全面解析HQL语句 非常详细直接的HQL语句的功能介绍” 描述:“非常详细直接实用的HQL语句的功能介绍看过的人保准都说好” 本篇文章将深入探讨HQL(Hibernate Query Language)的核心功能及其在数据查询...

    精通HQL.doc

    使用HQL,我们可以执行以下操作: 1. **检索类的所有对象**:HQL允许你获取特定类的所有对象。例如,`from Student` 将返回数据库中所有的Student对象。 2. **根据条件查询**:可以添加WHERE子句来指定查询条件,...

    HQL批量插入、更新和删除

    - **批量更新**:对于批量更新操作,可以使用HQL的`UPDATE`语句。例如,要更新所有用户的密码,可以执行如下HQL语句: ```java String hql = "UPDATE User SET password = :newPassword WHERE id = :userId"; ...

    HQL连接查询和注解使用总结

    ### HQL连接查询和注解使用总结 #### HQL连接查询概述 HQL(Hibernate Query Language)是一种面向对象的查询语言,它允许开发者以一种更自然的方式查询对象,而不是直接查询底层数据库表。HQL支持多种连接查询...

    HQL查询pdf资料

    HQL查询的基本结构包括关键字如`SELECT`、`FROM`、`WHERE`、`GROUP BY`、`HAVING`、`ORDER BY`等,这些关键字的使用与SQL非常相似,但是HQL还支持面向对象的特性,如属性路径表达式。 ##### 实体的更新与删除 在...

    精通hibernate HQL语言

    HQL,全称Hibernate Query Language,是Hibernate框架提供的一种面向对象的查询语言,它的语法结构与SQL相似,但主要针对对象和实体进行操作,而不是直接操作数据库表。HQL是Hibernate官方推荐的检索数据的主要方式...

    hibernate hql基本操作

    ### Hibernate HQL 基本操作详解 #### 一、HQL简介 HQL,即Hibernate Query Language,是Hibernate提供的一种强大的查询语言。虽然它的语法结构看起来与SQL类似,但其实质上是一种面向对象的语言,能够理解并处理...

    03-HQL实用技术.pdf

    ### HQL实用技术知识点概述 ...通过对以上知识点的学习,可以深入理解HQL在处理不同场景下的应用技巧,特别是关联关系的配置和HQL查询的使用。这些知识不仅有助于提高软件开发的效率,还能提升系统的健壮性和可维护性。

Global site tag (gtag.js) - Google Analytics