HQL Summary of Hibernate

Source: Internet
Author: User

Hibernate Run Process:

Hibernate role 1, Hibernate is a bridge between Java applications and relational databases, and she is responsible for mapping between Java objects and relational databases. 2. Hibernate internally encapsulates the operation of accessing the database through JDBC, providing an object-oriented data access API to upper-level applications. Hibernate API Introduction 1. Providing access to database operations (Session,transaction,query) 2. Configure Hibernate interface (configuration) 3. Callback Interface (interceptor,lifecycle,vaildatable) 4. Function interface for expansion (Usertype,composititeusertype, Identifiergenerator) the query and Criteria interface are the queries interface, the query instance wraps the HQL (hql:hibernate query language) queries, HQL is object-oriented, she refers to the class name and the class's property name Instead of the table name and field name. The criteria interface completely encapsulates a query statement based on a string, more object-oriented than the query ' interface , and she is adept at executing dynamic queries. The Find method of the session interface also has the right data query function, but she just executes some simple hql query statements shortcuts, far from the query interface powerful.
The direct from query is a mapping object, that is: querying the entire Mapping object all fields           String hql = "from Users";           Query query = session.createquery (HQL);                      list<users> Users = Query.list ();           for (Users user:users) {               System.out.println (user.getname () + ":" + user.getpasswd () + ":" + User.getid ());           }      the output is:   name1:password1:1  name2:password2:2  name3:password3:3  

  

 //  query single field  String hql = "Select NA           Me from Users ";                      Query Query  = Session.createquery (HQL);           List  <String> list = Query.list ();  for   (String str:list) {System.out           . println (str); The output is: name1 name2 name3  
 //  query several of the fields  String hql = "Select           NAME,PASSWD from Users ";           Query Query  = Session.createquery (HQL);  //  L           ist<object[]> list = Query.list ();  for   (object[] object:list) {Strin               G name  = (String) object[0];                              string passwd  = (String) object[1];           SYSTEM.OUT.PRINTLN (name  + ":" + passwd); The output is: Name1:password1 name2:password2 name3:password3  
//query Several of these fields, add new Map (), and note that the M in the map is lowercase. There is no need to import the package, so the list stored by query.list () is no longer the default object array, but the map collectionString hql = "Select New Map (NAME,PASSWD) from Users"; Query Query=session.createquery (HQL); //The default query list contains an object array, but in this list it is no longer the default object array, but the map collectionlist<map> list =query.list ();  for(Map user:list) {//all the field values in a record are an element in the map, the key is the string 0,1,2,3....,value is the field value//If you change hql to: String hql = "Select New map (name as username,passwd as password) from Users", then key will not be string 0,1,2 ... but "Usern Ame "," password ".String name = (string) user.get ("0");//get ("0"); is get (key), note: 0,1,2 is a string, not an orthopedicString passwd = (string) user.get ("1"); SYSTEM.OUT.PRINTLN (Name+ " : " +passwd); }           /**the output is: Name1:password1 name2:password2 name3:password3*/  
 PackageCom.domain;  Public classMyUser {PrivateString username; PrivateString password; //because: String hql = "Select New Com.domain.MyUser (NAME,PASSWD) from Users"; You must have a constructor that takes 2 arguments     PublicMyUser (String username,string password) { This. Username =username;  This. Password =password; }               PublicString GetUserName () {returnusername; }        Public voidSetusername (String username) { This. Username =username; }        PublicString GetPassword () {returnpassword; }        Public voidSetPassword (String password) { This. Password =password; }                 }  
//The list stored by query.list () is no longer the default object array, but a custom class myuser, which must be added with the package name, String hql = "from users", and the users class must be added to the package name.   But because again Users.hbm.xml String hql = "Select New Com.domain.MyUser (NAME,PASSWD) from Users"; Query Query=session.createquery (HQL); //The default query list contains an object array, but in this list it is no longer the default object array, but the MyUser object.List<myuser> myusers =query.list ();  for(MyUser myuser:myusers) {String name=Myuser.getusername (); String passwd=Myuser.getpassword (); SYSTEM.OUT.PRINTLN (Name+ " : " +passwd); }           /**the output is: Name1:password1 name2:password2 name3:password3*/  
//conditional query, parameter index value starting at 0, index position. Setting parameters by Setstring,setparameterString hql = "from Users where name=?" and passwd=? "; Query Query=session.createquery (HQL); //1th Way//query.setstring (0, "name1"); //query.setstring (1, "Password1"); //2nd WayQuery.setparameter (0, "name1", hibernate.string); Query.setparameter (1, "Password1", hibernate.string); List<Users> list =query.list ();  for
 //  conditional query, set parameters by SetProperties  Str              ing hql = "from Users where Name=:username and passwd=:p assword"  = Session.createquery (HQL);  // myuser class must be the same as: username and: Password corresponds to  MyUser MyUser = new  MyUser ("name1", "Password1" );              Query.setproperties (MyUser);              List  <Users> list = Query.list ();  for   (Users users:list) {System              . Out.println (Users.getid ()); }  
The expressions allowed in the WHERE clause include most of the kinds of expressions you can use in sql: math operator +,-, *,/binary comparison operator =, >=,<=, <>,! =, like logical operator and, or, notin, not in, between, was null, is not NULL, was empty, is isn't empty, member of and not member of "simple" case, case ... when ... then ... else ... end, and "search" case, case when ... then ... else ... "End string connector ..... | | ... or concat (...,...) Current_date (), Current_time (), Current_timestamp () second (...), Minute (...), hour (...), day (...), month (...), Year ( ...), EJB-QL 3.0 defined by any function or operation: substring (), trim (), lower (), upper (), Length (), locate (), ABS (), sqrt (), bit_length () COALESCE () and Nullif () cast (...), whose second parameter is the name of a hibernate type, and extract (...), as long as ANSI cast () and extract () are supported by the underlying database What database supports SQL scalar functions such as sign (), trunc (), RTrim (), sin () jdbc parameter incoming? named parameter: Name,: start_date,: X1sql Direct constant ' foo ', 69, ' 1970-01-01 10:0 0:01.0 ' Java public static final type constant eg. Color.tabby

Category for all products provided by the provider with the query number "S0002"

 Public void qrycategoriesbysupply () {        session session=this. getsession ();        List<category>list=session.createquery ("Select P.category from Product p where p.suppers.no=?") )        . SetString (0, "S9002")        . List ();          for (Category c:list) {            System.out.println (C.getname ());        }        Session.close ();    }

Queries can provide vendor information for a product (using elements processing)

Query the number and name of each provider for a product named "TCL SHE8533" (partial attribute query)

  Public voidQrynumname () {//Select P.suppers.no,p.suppers.name from Product p where p.name= ' Kodako '//Select S.no,s.name from Supper s where s.products.name= ' Kodako 'Session session= This. getsession (); List List=session. CreateQuery ("Select P.suppers.no,p.suppers.name from Product p where p.name= ' Kodako '"). List ();  for(Object obj:list) {object[] Object=(object[]) obj; System.out.println (object[0]+ ":" +object[1]); } session.close (); }

Queries can provide vendor information for a product (using elements processing)

 Public void qrysupplybyelements () {    session session=this. getsession ();    Product Product= (product) session.get (product.  Class, "0002");        List<Supper> list=session        . CreateQuery ("from Supper s where:p roduct in elements ( s.products)        . Setentity ("Product", product).        list ();              for (Supper s:list) {        System.out.println (S.getname ());    }    Session.close ();}

Using QBE query, the price is 2680, the name is "Fuji S6500" Products

 Public void qryprobyqbe () {    product product=new  Product ();    Product.setprice (2680f);    Product.setname ("Fuji S6500");        Session session=this. getsession ();    List<Product> list=session        . Createcriteria (Product. class )        . Add (example.create (product))        . List ();              for (Product p:list) {        System.out.println (p.getname ()+ ":" +P.getprice ());    }    Session.close ();}

Reprint Address: http://blog.csdn.net/xinyu0100/article/details/5385989

HQL Summary of 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.