Save Record
Session.save (customer);
Query based on PRIMARY key
Customer customer = (customer) session.get (customer). Class , 1= (customer) session.load (customer). Class, 1);
The difference between get and load: (Interview question)
1. Time to send sql:
Load This method employs a technique. Lazy load (lazy loading). When you really use this object's data. (The object's data does not include a primary key)
Get this method is retrieved immediately. When the Session.get () method is executed, the SQL statement query is sent immediately.
2. Returned objects:
The Load method returns a proxy object.
The Get method returns a real object.
3. Query for a nonexistent data:
The Load method throws an exception: Objectnotfoundexception.
The Get method returns NULL, throwing an exception when calling the method: Nullpointexception.
Modify a record
// 1 How to create objects manually new Customer (); Customer.setid (2); Customer.setname ("Cang teacher"); session.update (customer); // this way if there is no property set, the default value of this property is saved (bad)
// 2 First Query and then modify the way (recommended way) Customer customer = (customer) session.get (customer). Class, 1); Customer.setname ("Sister Feng"); session.update (customer) ;
Deleting records
// There are two ways to delete a record: // 1 How to create objects manually New customer (); Customer.setid (2); Session.delete (customer);
// 2 How to query and delete first Customer customer = (customer) session.get (customer). Class, 1); Session.delete (customer);
Query all
HQL:Hibernate Query Language
// Object-oriented notation Query query = Session.createquery ("from Customer where name =?") ); Query.setparameter (0, "Cang teacher"); Query.list ();
QBC: Query bycriteria (conditional query)
Criteria = Session.createcriteria (Customer. Class); Criteria.add (Restrictions.eq ("name", "Sister Feng")); List<Customer> list = Criteria.list ();
Sql
// The first way SQLQuery query = Session.createsqlquery ("SELECT * from Customer"); List<Object[]> list = query.list (); // The second way SQLQuery query = Session.createsqlquery ("SELECT * from Customer"); query.addentity (Customer. class ); List<Customer> list = Query.list ();
Hibernate-based CRUD operations