The basic common small examples of hql in Hibernate, single table query and multiple table query

Source: Internet
Author: User
Tags generator rollback

<span style= "Font-size:24px;color: #3366ff;" > This article implements the following functions of HQL:</span>
/**
 * HQL Syntax:
 *   1) Single table query
 *   	 1.1 Full Table Query
 *       1.2 Specify field query
 *       1.3 excluding duplicate records
 *       1.4 piece Query (emphasis)
 *       1.5 paging Query
 *       1.6 aggregation Query
 *       1.7 query Sort
 *       1.8 Group Inquiry
 *       1.9 After grouping filter
 *       
 *   2 Multi-table Query
 *       1.1 Inner Connection
 *       1.2 left outer/right outer connection   
* *
</span>


First, you configure the hibernate XML file so that two databases are linked, a one-to-many mapping connection

Employee.hbm.xml

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">


Dept.hbm.xml

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">


Create two more entity classes

Employee.java

Package star.july.d_hql;
	public class Employee {private int id;
	private String name;
	Private String gender;
	Private String title;
	Private String Email;
	private double salary;
	
	Private Dept Dept = new Dept ();
	Public Dept getdept () {return Dept;
	public void Setdept (Dept Dept) {this.dept = Dept;
	public int getId () {return id;
	The public void setId (int id) {this.id = ID;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public String Getgender () {return gender;
	} public void Setgender (String gender) {This.gender = gender;
	Public String GetTitle () {return title;
	public void Settitle (String title) {this.title = title;
	Public String Getemail () {return email;
	public void Setemail (String email) {this.email = email;
	Public double getsalary () {return salary;
	The public void Setsalary (double salary) {this.salary = salary;
	@Override public String toString () {	Return "Employee [id= + ID +", name= "+ name +", gender= "+ Gender +", title= "+ title +", email= "+ email +",
	Salary= "+ salary +"];
 }
	
	
}




Dept.java

Package star.july.d_hql;

Import Java.util.HashSet;
Import Java.util.Set;

public class Dept {
	private int id;
	Private String deptname;
	Private set<employee> Employee = new hashset<employee> ();
	public int getId () {return
		ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String Getdeptname () {return
		deptname;
	}
	public void Setdeptname (String deptname) {
		this.deptname = deptname;
	}
	Public set<employee> GetEmployee () {return
		Employee;
	}
	public void Setemployee (Set<employee> employee) {
		This.employee = employee;
	}
	
	
}	



Final Test HQL:

Demo.java

Package star.july.d_hql;
Import java.util.List;

Import Java.util.Set;
Import Org.hibernate.Query;
Import org.hibernate.Session;
Import org.hibernate.Transaction;

Import Org.junit.Test;
Import Star.july.util.HibernateUtil;
 /** * HQL Grammar: * 1) Single table query * 1.1 Full Table Query * 1.2 Specify field Query * 1.3 excluding duplicate records * 1.4 piece Query (emphasis) * 1.5 paging query * 1.6 Aggregate Query * 1.7 Query Sort * 1.8 Group Inquiry * 1.9 Group after filter * * 2) Multi-table Enquiry * 1.1 Inner link * 1 .2 LEFT OUTER join/RIGHT OUTER JOIN * */public class Demo {@Test public void Test () {Session session = Hibernateutil.get
		Session ();
		Transaction ts = session.gettransaction ();
			try{Ts.begin ();
			HQL basic syntax//1, create a Query object//parameter: HQL statement String hql = "Select E from Employee e where id = 1";
			Query query = session.createquery (HQL);
			2. Execute Query//2, 1 package all list<employee> emp = Query.list ();
			for (Employee e:emp) {System.out.println (e); }//2, 2 package one (first) employee Empl = (employee) qUery.uniqueresult ();
			
			System.out.println (EMPL);
			
		Ts.commit ();
			}catch (Exception e) {e.printstacktrace ();
		Ts.rollback ();
		}//Tanku query @Test public void Test3 () {Session session = Hibernateutil.getsession ();
		Transaction ts = session.gettransaction (); try{Ts.begin ();//* 1) Single table query//* 1.1 Full Table Query//String HQL = "from STAR.JULY.D_HQL.
			Employee ";
			
Auto-import: Automatically to burst, automatically under each package to search for the corresponding class of packages, multiple classes of the same name of the report conflict//String HQL = "Select E from Employee e";
			
* 1.2 Specify field query//return object array//String HQL = "Select E.name,e.title from Employee e";
			
* 1.3 excluding duplicate records//String HQL = "SELECT DISTINCT (e.gender) from Employee e"; * 1.4 piece Query (emphasis) (where)//logical conditions: and OR//fuzzy query: like:% _//Comparison query: < > <= >= between and <
>//NULL query: Is NULL, are not null, = ',<> ';
String hql = "Select E from Employee e where name like ' Zhang% '"; String hql = "Select E from Employee e where e.gender is null or e.geNder= ' ";
			* 1.5 Paging query/* String HQL = "from Employee";
			Query query = session.createquery (HQL);
			Set start reading row query.setfirstresult (0); How many messages per page query.setmaxresults (3); *///* 1.6 aggregate query//avg,count,max,min,uniqueresult//String HQL =
			
"Select Max (e.salary) from Employee e";
			
			
* 1.7 Query sort//order by//desc: Descending ASC: Ascending//String HQL = "Select E from Employee e-id desc";
		
* 1.8 grouped query//String HQL = "Select e from Employee e Group by E.gender";  * 1.9 After grouping filter String hql = "Select E from Employee e where e.gender are not null and e.gender<> ' group"
			
			by E.gender has count (e.gender) >1 ";
			
			
			Query query = session.createquery (HQL);
			Collection Object List<object> e = Query.list ();
			for (Object emp:e) {System.out.println (EMP);
			}//Object array/* list<object[]> objects = query.list (); For (object[] object:objects) {for (Object Obj:objeCT) {System.out.print (obj);
			} System.out.println ();
			*//Encapsulate an object/*object unique = Query.uniqueresult ();
		System.out.println (unique); */Ts.commit ();
			}catch (Exception e) {e.printstacktrace ();
		Ts.rollback ();
			}//Multiple table query @Test public void Test2 () {Session session = Hibernateutil.getsession ();
			Transaction ts = session.gettransaction ();
				
				try{Ts.begin (); /** * Step * 1, determine which objects to query *2, determine what to wipe out what properties * 3, determine the connection conditions *4, business conditions * *//1, the Internal Connection query//effect: Only the data to meet the conditions will be displayed 
				Come out/check employees and their departments: Show employee name, department name//String HQL = "Select E.name,d.deptname from Employee E, Dept D where e.dept.id=d.id";
				
				
				Another way of writing//String hql = "Select E.name,d.deptname from Employee e inner join e.dept d"; Left OUTER JOIN//Effect: First display left table, right table data match display, mismatched then show null//query All Department employees (departments that do not have employees to display) String hql = "Select D.deptname, E.name fro
				
				M Dept D left outer join D.employee E "; Right outer join//String HQL = "Select D.deptname,e.name from Employee e right outer join e.dept D ";
				
				Query query = session.createquery (HQL);
				/*list<object> Object = Query.list ();
				for (Object obj:object) {System.out.println (obj);
				}*/list<object[]> objects = Query.list ();
					For (object[] object:objects) {for (Object obj:object) {System.out.print (obj);
				} System.out.println ();
				
			} ts.commit ();
				}catch (Exception e) {e.printstacktrace ();
			Ts.rollback ();
 }
		}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.