Hibernate series notes (2) --- Hibernate core API, hibernate5.2 Chinese api

Source: Internet
Author: User

Hibernate series notes (2) --- Hibernate core API, hibernate5.2 Chinese api

Core APIs of Hibernate

Generally, we will follow the following process when operating through hibernate. Next I will explain each step:

1 public void testInsert () {2 // (1) instantiate configuration object loading ing file loading hibernate. cfg. xml 3 Configuration configuration Configuration = new Configuration (). configure (); 4 // (2) create session factory 5 SessionFactory sessionFactory = configuration. buildSessionFactory (); 6 // (3) create Session 7 session Session = sessionFactory. openSession (); 8 // (4) Enable Transaction 9 transaction Transaction = session. beginTransaction (); 10 11/* 12 * write your own logic code 13 */14 15 // submit transaction 16 transaction. commit (); 17 session. close (); 18 sessionFactory. close (); 19}

(1) instantiate the configuration object configuration

This step is used to load the core configuration file

   There are two core configurations:
Hibernate. properties
Load: Configuration configuration Configuration = new Configuration ();
Hibernate. cfg. xml:
Load: Configuration configuration = new Configuration (). configure ();

(2) create a session factory sessionFactory

The Configuration object generates the SessionFactory object based on the current Configuration information,

The SessionFactory object stores the current database configuration information, all mappings, and predefined SQL statements.

SessionFactory objects are thread-safe, and SessionFactory is also responsible for maintaining Hibernate's second-level cache,

The SessionFactory object maintains the Connection pool based on the database information and creates a Session (equivalent to a Connection) object.

(3) create a session Object(Equivalent to JDBC Connection)

Session is a single-threaded object for interaction between applications and databases. It is the center of Hibernate operation and is thread insecure.

All persistent objects can be persisted only under session management. Session objects have a level-1 cache.

Before explicit flush execution, the data of all persistent operations is cached at the session object. After the persistence class is associated with the Session, it has the persistence capability,

Session maintains the Hiberante Level 1 cache.

The session Object provides many methods for adding, deleting, and modifying differences:

Save ()/persist (): Add
Update (): Modify
SaveOrUpdate (): Add and modify objects
Delete (): delete an object
Get ()/load (): query by primary key
CreateQuery (): Creates a Query interface and writes HQL statements.
CreateSQLQuery (): Creates a SQLQuery interface to write database operation objects for SQL statements.
CreateCriteria (): returns a Criteria interface. Condition query.

(4) Extraction Tool

Because we often need to add, delete, modify, and query operations in project development, we need this session object. At this time, we can turn her into a tool class.

1 public class HibernateUtils {2 3 private static Configuration configuration; 4 5 private static SessionFactory sessionFactory; 6 7 static {8 configuration = new Configuration (). configure (); 9 10 sessionFactory = configuration. buildSessionFactory (); 11} 12 public static Session getSession () {13 return sessionFactory. openSession (); 14} 15} 16/* 17 * through this tool class, as long as you each HibernateUtils. getSession18 * to get the session Object 19 */

(5) Enable Transaction object

  Get: Transaction tx = session. beginTransaction ();

Common Methods:
Commit (): Submit the associated session instance
Rollback (): cancels a transaction.
WasCommitted (): checks whether the transaction is committed.

If transactions are not enabled, each Session operation is equivalent to an independent transaction.

6. Query object
 Query represents an object-oriented Hibernate Query operation.
Session. createQuery receives an HQL statement
HQL is the abbreviation of Hibernate Query Language. The syntax is similar to the SQL syntax, but it is fully object-oriented.

Example

// 1. query all data public void testQuery () {// here is the reference class written in the note to obtain the session object Session session = HibernateUtils. getSession (); Transaction transaction = session. beginTransaction (); String hql = "from Customer"; // class name Query query = session. createQuery (hql); List <Customer> MERs = query. list (); System. out. println (MERS mers); transaction. commit (); session. close ();}}
Query all data
// Batch insert public void testBathInsert () {Session session = HibernateUtils. getSession (); Transaction transaction = session. beginTransaction (); for (int I = 0; I <1000; I ++) {Customer customer = new Customer (); customer. setName ("James _" + I); customer. setAddr ("Yuhang District _" + I); customer. setCity ("Hangzhou _" + I); customer. setAge (I); session. save (customer);} transaction. commit (); session. close ();
Batch insert data
1 // query by page 2 public void testQueryByPage () {3 Session session = HibernateUtils. getSession (); 4 Transaction transaction = session. beginTransaction (); 5 6 // Query all data 7 String hql = "from Customer"; 8 query Query = session. createQuery (hql); 9 10 // set the query condition 11 query. setFirstResult (20); // you can specify the start query position as 12. setMaxResults (20); // query length: 13 14 List <Customer> MERs = query. list (); 15 System. out. println (MERS mers); 16 17 18 transaction. commit (); 19 session. close (); 20}
Paging Query
1 // use the select keyword to query the specified attribute and the corresponding column 2 public void testQuerySelect () {3 Session session = HibernateUtils. getSession (); 4 Transaction transaction = session. beginTransaction (); 5 // since it is new Customer (name, age), you need to use this constructor 6 String hql = "select new Customer (name, age) from Customer "; 7 8 Query query = session. createQuery (hql); 9 10 List <Customer> MERs = query. list (); 11 System. out. println (MERS mers); 12 13 transaction. commit (); 14 session. close (); 15}
Select a specific column
1 // use the where condition 2 public void testQueryParamter () {3 Session session = HibernateUtils. getSession (); 4 Transaction transaction = session. beginTransaction (); 5 6 String hql = "from Customer where name =? And age =? "; 7 8 Query query = session. createQuery (hql); 9 query. setParameter (0, "James _ 4"); 10 query. setParameter (1, 4); 11 12 List <Customer> MERs = query. list (); 13 System. out. println (MERS mers); 14 15 transaction. commit (); 16 session. close (); 17}
Where condition Query

7. Criteria (conditional query interface)

It can achieve the same effect as Query.

Example

1 // query all 2 public void testQueryAll () {3 4 // obtain the Session object 5 Session session = HibernateUtils. getSession (); 6 // start Transaction 7 transaction Transaction = session. beginTransaction (); 8 // 9 Criteria criteria = session. createCriteria (Customer. class); 10 11 List <Customer> MERs = criteria. list (); 12 System. out. println (MERS mers); 13 14 transaction. commit (); 15 session. close (); 16}
Query all  
1 // query by page 2 public void testQueryByPage () {3 // obtain the Session object 4 Session session = HibernateUtils. getSession (); 5 // start Transaction 6 transaction Transaction = session. beginTransaction (); 7 8 Criteria criteria = session. createCriteria (Customer. class); 9 criteria. setFirstResult (30); 10 criteria. setMaxResults (20); 11 12 List <Customer> MERs = criteria. list (); 13 System. out. println (MERS mers); 14 15 transaction. commit (); 16 session. close ();
Paging Query
1 // condition query 2 public void testQueryByCondition () {3 // obtain the Session object 4 Session session = HibernateUtils. getSession (); 5 // start Transaction 6 transaction Transaction = session. beginTransaction (); 7 Criteria criteria = session. createCriteria (Customer. class); 8 9 // create a condition object 10 Criterion criterion = Restrictions. eq ("name", "James _ 4"); 11 12 // load the query condition object to the query object 13 criteria. add (criterion); 14 15 List <Customer> MERs = criteria. list (); 16 System. out. println (MERS mers); 17 18 transaction. commit (); 19 session. close (); 20}
Conditional Query

This article is about it. Thank you for your advice!

 

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.