Hibernate is primarily a framework for interacting with databases, and you want to manipulate relational databases in an object-oriented language, as in the next two ways:
HQL Statement : Object-oriented Query language, object names are case-sensitive. And unlike SQL, this is where the object is queried, not the table, and polymorphism is supported. HQL mainly through the query operation
Criteria Class : is an object-oriented query, the main query criteria.
One, HQL statement:
For example, we want to query a record (object) based on the Name property:
static void query (String name) {Session s = null;try{s = Hibernateutil.getsession ();//Open sessionstring hql = "from User as User where user.name=? "; /write HQL statement query query = s.createquery (HQL);//Open Query Query.setstring (0, name);//Assign a value to the attribute in the HQL statement, 0 for the first question mark (?) Property List<user > list = Query.list (); Query to a listfor (User user:list) {System.out.println (User.getname ()) that satisfies the condition,//Then output}}finally{if (s!=null) {s.close ();}}}
Note that the conditions that are met here are a list.
In addition, if the HQL statement above can create a problem with an index, so we can modify the above code to:
String hql = "from user as user where user.name=:name";//write HQL statement query query = s.createquery (HQL);//Open Query Query.setstring ("n Ame ", name);//Assign a value to a property in the HQL statement, and 0 for the first question mark (?) property
If we can make sure that the query gets only one result.
We can put the code:
List <User> list = Query.list (); for (User user:list) {System.out.println (User.getname ());}
Change into a sentence:
User U = (user) query.uniqueresult (); System.out.println (U.getname ());
Second, the criteria category
We design a CRI (String name) function:
static void Cri (String name) {Session s = null;try{s = Hibernateutil.getsession (); Criteria ctr = S.createcriteria (User.class), Ctr.add (Restrictions.eq ("name", name)); Add find Condition: equal to name Ctr.add (restrictions.lt ("Birthday", new Date ()));//Add find condition: less than inside date list<user> list = Ctr.list (); for (User user:list) {System.out.println (User.getname ());}} Finally{if (s!=null) {s.close ();}}}
Hibernate series (iv): Hibernate two ways of querying: HQL and Criteria