Hibernate's query methods are commonly divided into three main types: HQL, QBC (query by Criteria), and using native SQL queries
HQL Query
hql (Hibernate query Language) provides a rich and flexible way of querying, and querying using HQL is also the official recommended query method for hibernate.
HQL is the same syntax structure as SQL statements, so it can be used quickly. Using HQL, you need to use the query object in Hibernate, which specializes in HQL-mode operations.
// The From is followed by the object to be queried, not the table Query query = session.createquery (HQL); List<User> userlist =for(User user:userlist) { System.out.println ( User.getusername ()); } session.gettransaction (). commit ();
gets an Incomplete object session.begintransaction (); String hql= "Select UserName from User"; Query Query=session.createquery (HQL); List NameList=query.list (); for(Object obj:namelist) {System.out.println (obj);} session.gettransaction (). commit ();//multiple attributes, you need to use object[] to receivesession.begintransaction (); String hql= "Select Username,userpwd from User"; Query Query=session.createquery (HQL); List NameList=query.list (); for(Object obj:namelist) {object[] array= (object[]) obj;//turn into object[]System.out.println ("Name:" + array[0]); System.out.println ("PWD:" + array[1]); } session.gettransaction (). commit ();
= "SELECT count (*), Max (ID) from User"==for(Object obj:namelist) { = (object[]) obj; System.out.println ("Count:" + array[0]); System.out.println ("max:" + array[1]);} Session.gettransaction (). commit ();
More wording select distinct name from Student; Select Max (age) from Student; Select count (age), age from Student group by age; From Student order by age;
hql placeholder and paging session.begintransaction (); String SQL= "Select Uname,password from User where enable=?"; Query Query=session.createquery (SQL); //placeholder ContentQuery.setboolean (0,true); //First few startQuery.setfirstresult (0); //Display numberQuery.setmaxresults (2); List<Object[]> list =query.list (); for(object[] user:list) {System.out.println (user[0]+ "--" +user[1]); } session.gettransaction (). commit ();
Native SQL query
addentity () example session.begintransaction (); String SQL = "Select Id,username,userpwd from T_user" // Addentity () can tell hibernate what type you want to encapsulate as an object, and then automatically encapsulate SQLQuery query = session.createsqlquery (SQL). Addentity (User. Class ); List <User> list = Query.list (); for (User user:list) { System.out.println (User.getusername ()); } session.gettransaction (). commit ();
uniqueresult example Session.begintransaction (); String SQL = "Select Id,username,userpwd from t_user where id = 2" ; SQLQuery query = session.createsqlquery (sql). Addentity (User. Class ); User User =