Hibernate Basics (ii)

Source: Internet
Author: User

Entity rules in Hibernate

Considerations for creating entity classes:

1. Persistent classes provide parameterless constructors

2. Member variable private provides a common get set method

3. Properties should use wrapper class Integer, Float, double, etc. (if not assigned with int will default 0 if integer is not assigned default null)

4. The persistence class needs to provide an OID, corresponding to the primary key column in the database

5. Do not use Finall to modify the class

Primary KEY Type:

1. Natural primary KEY (uncommon) if the business requires a column that must have and is not duplicated, it can be used as a primary key

2. Proxy primary key (common) if you don't have business logic, you only need a number to use this.

Primary key generation Policy:

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE hibernate-mapping SYSTEM "Http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping Package= "Com.hibernate.domain">        <classname= "User"Table= "User">        <!--ID: Primary Key, Name: property name, Column: Field name -        <IDname= "UserId"column= "UserId">            <!--Generator: Primary key Generation Policy class: How to generate the value of the primary key: 1, native: Automatic growth, will automatically switch according to the current database 2, identity:mysql own maintenance of the primary key, input does not need to specify            Primary key 3, sequence:oracle token 4, uuid:32 bit string 5, Assigned: Custom string 6, Foreign: foreign key 7, increment:hibernate own query maximum id+1 to insert -            <Generatorclass= "Native"/>        </ID>           </class></hibernate-mapping>

Object state in Hibernate

Instantaneous state

No ID, not associated with session

Persistent state

has ID, associated with session

Free | managed state

has ID, not associated with session

 Public class Main {    publicstaticvoid  main (string[] args) {        =  Hibernateutils.opensession ();         New // instantaneous state no ID is not associated        with session User.setusername ("haha");         // persistent state has ID associated with session        // Free | Managed status has ID, no associated session     }}

First-level cache in Hibernate

To improve operational efficiency in the database

 Public classMain { Public Static voidMain (string[] args) {Session session=hibernateutils.opensession (); User U1= Session.get (User.class, 1); User U2= Session.get (User.class, 1); User U3= Session.get (User.class, 1); User U4= Session.get (User.class, 1); User U5= Session.get (User.class, 1); System.out.println (U3==U4);//trueSession.close (); }}

First execution steps:

1. Call the Get query

2. Sending SQL statements

3.resultSet back

4. Assemble the contents of the ResultSet into a user object

5. Save to session Cache

6. Object return

Second execution step:

1. See if there is a user object with ID 1 first from the cache

2. If there is a direct return in the cache

    

Transactions in Hibernate

Transaction characteristics: ACID (atomicity, consistency, isolation, persistence)

Transaction Concurrency issues:

Dirty read: Read the data that is being manipulated yet to be committed.

Non-REPEATABLE READ: two consecutive reads, inconsistent data. (Someone in the middle may have modified it)

Illusion | Virtual reading: The user table is deleted from the whole table, the result of a person added one in.

Isolation level of the transaction:

READ UNCOMMITTED: Dirty read, non-repeatable read, Phantom read

Read Committed: Can resolve dirty read, cannot resolve non-repeatable read, Phantom read

REPEATABLE READ: Can resolve dirty read, non-repeatable read, not solve Phantom read (MySQL default level)

Serialization: All can be solved, reduce efficiency

Specify the isolation level of the database in hibernate:

In the Hibernate.cfg.xml global configuration

<!--          0001 1: READ UNCOMMITTED         0010 2: Read Committed         0100 4: Repeatable Read          --         <Name  = "hibernate.connection.isolation">4</Property> 

To manage transactions in a project:

The transaction is opened before the business starts, the transaction commits after the business executes, an exception occurs during execution, and the transaction is rolled back.

In order to guarantee the consistency of the session object, we need to use getcurrentsession (); Need to configure global configuration file

<!---        <name = "Hibernate.current_session_ Context_class ">thread</Property>
        Session Session1 = hibernateutils.getcurrentsession ();         = hibernateutils.getcurrentsession ();        System.out.println (Session1//true

Returns the same session bound to the thread.

Session objects obtained through the Getcurrentsession () method will automatically close the session when the transaction is committed, without our manual session.close () shutdown.

 Public class Main {    publicstaticvoid  main (string[] args) {        =  Hibernateutils.getcurrentsession ();         = session.begintransaction ();         Try {            session.save (new User ("haha", "hh", 18, "male"));         Catch (Exception e) {            trans.rollback ();        }        Trans.commit ();    }}

Batch queries in Hibernate

HQL query (Hibernate query Language) main usage

 Public classMain { Public Static voidMain (string[] args) {Session session=hibernateutils.opensession (); //Query UserListString hql = "from User"; Query Query=session.createquery (HQL); List<User> users =query.list ();        System.out.println (users); //condition query a userString HQL1 = "from User where UserId = 5"; Query Query1=session.createquery (HQL1); User User=(User) Query1.uniqueresult ();        System.out.println (User.getusername ()); //placeholderString hql2 = "from User where UserName =: UserName and age =: Age"; Query Query2=session.createquery (HQL2); Query2.setparameter ("UserName", "Wuhan University Lang"); Query2.setparameter ("Age", 18); User User2=(User) Query2.uniqueresult ();        System.out.println (User2.getusername ()); //Paging QueryString hql3 = "from User"; Query Query3=session.createquery (HQL3); Query3.setfirstresult (0); Query3.setmaxresults (10); List<User> List3 =query3.list ();    System.out.println (LIST3); }}

Criteria Query (single table query-obsolete)

 Public classMain { Public Static voidMain (string[] args) {Session session=hibernateutils.opensession (); //Query ListCriteria = Session.createcriteria (User.class); List<User> list =criteria.list ();        SYSTEM.OUT.PRINTLN (list); //Query aCriteria criteria1 = Session.createcriteria (User.class); Criteria1.add (Restrictions.eq ("UserId", 1)); User User1=(User) Criteria1.uniqueresult ();        System.out.println (User1.getusername ()); //List of pagesCriteria criteria2 = Session.createcriteria (User.class); Criteria2.setfirstresult (0); Criteria2.setmaxresults (10); List<User> List2 =criteria2.list ();    System.out.println (LIST2); }}

Native SQL query

 Public classMain { Public Static voidMain (string[] args) {Session session=hibernateutils.opensession (); String SQL= "SELECT * from User"; SQLQuery Query=session.createsqlquery (SQL); List<User> list =query.list ();        SYSTEM.OUT.PRINTLN (list); SQLQuery Query1= Session.createsqlquery ("SELECT * from user where UserID =: userid"); Query1.setparameter ("UserId", 1); Query1.addentity (User.class); User User=(User) Query1.uniqueresult ();    System.out.println (User.getusername ()); }}

Hibernate Basics (ii)

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.