Multi-table query for "Hibernate" hibernate

Source: Internet
Author: User

In the article "Hibernate" Hibernate's clustering query, group query, sorting and time difference (click to open link), it has been described how to use HQL statements instead of SQL statements. queries that cluster queries, group queries, sorting and time differences, at the same time, point out that hql can do whatever it takes to replace SQL statements. I originally thought that the HQL statement the Multi-table query, must first to the inside the entity to make the Java and the XML change, actually does not need, the same is a sentence HQL statement can fix the thing. SQL's multi-table query has been implemented in the "Mysql" using internal connections and nested queries to implement a multi-table query. The basic concept of the primary key and the foreign key (click the Open link) has spoken.

For example, the following SQL statement:

Select T1. Title,t1. Contentfrom Blog as T1, usertable as T2where t1.userid=t2.id and T2.username= ' a '

Convert to HQL statements such as the following:

String hql= "Select T1.title,t1.content from Blog as t1,usertable as T2 where t1.userid=t2.id and T2.username= ' a '"  List <Object> resultlist = Session.createquery (hql). List ();  for (int i = 0; i < resultlist.size (); i++) {      object[] obj = (object[]) resultlist.get (i);      System.out.println (obj[0]+ "," +obj[1]);  }

The core idea is to write the table in the SQL statement as the entity of Hibernate. The fields in the SQL statement, the columns, the member variables of the entities written as hibernate, must be marked with As for t1,t2 at the same time, and cannot be simplified using the blog.xx field. As above, is blog,usertable two tables into the T1,T2 tag, the SQL fields, columns, tables corresponding to hibernate entity member variables, entities to query.

The result of Hibernate query is a list that holds the object array, which means that each item of list is an object array, and the nth item of the object array is the nth item of the corresponding query result.

Be able to proceed with the next step.

The following is a sample to illustrate the multi-table query for the HQL statement.

, the blog recorded the user published blogs, usertable records the user's basic information.

The UserID in the blog table and the primary key ID of the usertable form an illumination integrity.


The two tables in Hibernate's javaproject species correspond to the following entities, for example:

Blog.java

Import javax.persistence.*; @Entity @table (name = "blog") public class Blog {private int id;private String title;private Str ing content;private int userId; @Id @generatedvaluepublic int getId () {return Id;} public void setId (int id) {this.id = ID;} @Column (name = "Title") public String GetTitle () {return Title;} public void Settitle (String title) {this.title = title;} @Column (name = "Content") public String getcontent () {return Content;} public void SetContent (String content) {this.content = content;} @Column (name = "userid") public int getUserId () {return userid;} public void Setuserid (int userId) {this.userid = userId;} @Overridepublic String toString () {return id + "," + title + "," + Content + "," + UserId;}}
Usertable.java

Import javax.persistence.*; @Entity @table (name = "Usertable") public class Usertable {private int id;private String username;private String password; @Id @generatedvaluepublic int getId () {return Id;} public void setId (int id) {this.id = ID;} @Column (name = "username") public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} @Column (name = "password") public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} @Overridepublic String toString () {return id + "," + Username + "," + Password;}}

At the same time, Hibernate.cfg.xml does the following configuration:

<?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 ">Be able to discover that this does not carry the designation of the completeness of the reference whatsoever.

Below, you want to query the users in usertable for username a. Published blog.

We know first to query the ID of the user who is username a. Then use this to find out the ID into the blog table query.

Complete this multi-table query with the SQL statement, then write this:

Select T1. Title,t1. Contentfrom Blog as T1, usertable as T2where t1.userid=t2.id and T2.username= ' a '
The results of the query are as follows:


This is written using Hibernate, where the code in the Hibernatemultitabletest.java is as follows:

Import Java.util.list;import Org.hibernate.*;import org.hibernate.cfg.*;class Dbdao {Private Session session;//constructor, Initialize session, equivalent to connection database public Dbdao () {//new configuration (). Configure () Yes, all the configuration in the hibernate.cfg.xml reads in//. Buildsessionfactory (). Opensession () is the creation of a session factory and instantiates sessionthis.session = new Configuration (). Configure (). Buildsessionfactory (). Opensession ();} Run the Query public query query (String hql) {return session.createquery (HQL);} Run INSERT, change public void Save (Object object) {Transaction Transaction = session.begintransaction (); Session.save (object); Transaction.commit ();} Run Delete public void Delete (Object object) {Transaction Transaction = session.begintransaction (); Session.delete (object); Transaction.commit ();} destructor, interrupt session, equivalent to interrupt database connection protected void Finalize () throws Exception {if (session.isconnected () | | session! = NULL) {SE Ssion.close ();}}} @SuppressWarnings ("Unchecked") public class Hibernatemultitabletest {public static void main (String args[]) {Dbdao db = NE W Dbdao (); List<object> Resultlist = Db.query ("Select T1.title,t1.content from Blog as t1,usertable as T2 where t1.userid=t2.id and T2.username= ' A ' "). List ();//HQL multi-table Query System.out.println (" usertable in username is a user, published content such as the following: "); System.out.println (); for (int i = 0; i < resultlist.size (); i++) {object[] obj = (object[]) resultlist.get (i); System.out.println ("title:" + obj[0]); System.out.println ("content:" + obj[1]); System.out.println ();}}}
The results of the operation are as follows:

Multi-table query for "Hibernate" hibernate

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.