Hibernate Study Notes and hibernate Study Notes

Source: Internet
Author: User

Hibernate Study Notes and hibernate Study Notes

1. Hibernate environment construction, configuration and HelloWorld

1.Build a Hibernate environment in Eclipse

Download the offline Hibernate jar package (jbosstools-4.4.final-updatesite-core.zip) -- "Help in Eclipse --" Install New Software -- "add...

2.Develop Helloworld for Hibernate

> Prepare the Hibernate Environment

1) import the required jar package, under the hibernate-release-4.2.4.Final \ lib \ required directory

2) Add the jar package of the database driver

> Hibernate development steps

1) Create the Hibernate configuration file hibernate. cfg. xml in the root directory of the class path.

<Hibernate-configuration> <session-factory> <! -- Configure the basic information for connecting to the database --> <property name = "connection. username "> root </property> <property name =" connection. password "> qiqingqing </property> <property name =" connection. driver_class "> com. mysql. jdbc. driver </property> <property name = "connection. url & quot;> jdbc: mysql: // localhost: 3306/hibernate </property>
<! -- Configure basic information about hibernate --> <! -- Database dialect used by hibernate --> <property name = "dialect"> org. hibernate. dialect. MySQLInnoDBDialect </property> <! -- Whether to print SQL statements on the console when performing the operation --> <property name = "show_ SQL"> true </property> <! -- Whether to format SQL --> <property name = "format_ SQL"> true </property> <! -- Specify the Automatic Data Table Generation Policy --> <property name = "hbm2ddl. auto"> update </property> <! -- Specify the associated. hbm. note that the xml file is not. in the format of/--> <mapping resource = "qi/hibernate/helloworld/News. hbm. xml "/> </session-factory>

2) create a persistent News class

Same as creating a normal JavaBean

3) Create the object-link ing file (automatically generated) News. hbm. xml in the an package.

<Class name = "qi. hibernate. helloworld. news "table =" NEWS "> <id name =" id "type =" java. lang. integer "> <column name =" ID "/> <! -- Specify the primary key generation method native: Use the local database method --> <generator class = "native"/> </id> <property name = "title" type = "java. lang. string "> <column name =" TITLE "/> </property> <property name =" author "type =" java. lang. string "> <column name =" AUTHOR "/> </property> <property name =" date "type =" java. SQL. date "> <column name =" DATE "/> </property> </class>

4) write the database access code through the Hibernate API

@ Testpublic void test () // 1. create a SessionFactory object SessionFactory sessionFactory = null; // 1 ). create a Configuration object: corresponds to the basic Configuration information of hibernate and the object relationship ing information configuration Configuration = new Configuration (). before configure (); // 4.0, create // sessionFactory = configuration. buildSessionFactory (); // 2 ). create a ServiceRegistry object: the newly added object of hibernate 4.x // any configuration and service of hibernate must be registered in this object before it becomes effective. serviceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); // 3 ). sessionFactory = configuration. buildSessionFactory (serviceRegistry); // 2. create a Session object Session = sessionFactory. openSession (); // 3. enable Transaction transaction Transaction = session. beginTransaction (); // 4. run the save operation News news = new News ("Java", "qiqingqing", new Date (new java. util. date (). getTime (); session. save (news); // 5. commit transaction. commit (); // 6. disable Session. close (); // 7. disable SessionFactory object sessionFactory. close ();}

> HibernateUnit test class writing (generally fixed)

public class HibernateTest {  private SessionFactory sessionFactory;  private Session session;  private Transaction transaction;
  @Before  public void init(){    Configuration configuration = new Configuration().configure();    ServiceRegistry serviceRegistry =       new ServiceRegistryBuilder().applySettings(configuration.getProperties())                       .buildServiceRegistry();    sessionFactory = configuration.buildSessionFactory(serviceRegistry);    session = sessionFactory.openSession();    transaction = session.beginTransaction();  }
  @After  public void destory(){    transaction.commit();    session.close();    sessionFactory.close();  }
  @Test  public void test() {    System.out.println("test");  }}

 Note:If you forget to configure the News. hbm. xml file in the hibernate. cfg. xml file, org. hibernate. InvalidMappingException: Unable to read XML is reported.

Ii. Session

1. Session cache (Hibernate level-1 cache): The same query operation is performed because the Session cache only executes SQL statements once.

1) three methods to operate Session cache

> Flush () makes the data in the data table consistent with the object state in the Session cache. To achieve the same effect, an SQL statement may be sent.

① In the commit () method of Transaction: Call the flush () method before committing the Transaction

② The flush () method may send SQL statements but will not commit transactions.

③ Note: flush () operations may also be performed before transactions are committed or explicit calls of flush ().

> If you perform the HQL or QBC operation, the flush () operation is performed first to obtain the latest records of the data table.

> Exception: if the record ID is generated by the database in auto-increment mode, the insert statement is immediately sent when the save () method is called. Because after the save () method, the Object ID must exist

> Refresh () will force the select statement to ensure that the State of the cached object is consistent with that of the corresponding record in the data table.

Note: After the refresh () method of the Session is called, if it is different from the expected result, you need to set the database transaction isolation level of Hibernate. The settings are as follows in the Hibernate. cfg. xml file.

<! -- Set the transaction isolation level of Hibernate --> <property name = "connection. isolation"> 2 </property>

> Clear (): If two identical get () queries call the clear () method of the Session after the first time, two SQL statements are sent.

2) Core Session Method

> Save () method: changes a temporary object to a persistent object.

Purpose: ① assign an id to the object ② an insert statement will be sent during the flush () cache ③ the id set before the save () method is invalid ④ the id of the persistence object cannot be modified, if you reset the id after the save () method, an exception is reported.

> Persist () method: the insert operation is also executed. Unlike the save () method, if the id is set before the persist () method is called, the insert statement is not executed, and an exception is thrown.

>Get () VS load () method:

① When the get () method is executed, the object will be loaded immediately. When the load () method is executed, if the object is not used, the query operation will not be executed immediately, and a proxy object will be returned, namely:Get () is instant retrieval load () is delayed Retrieval

② If the Session has been closed before the proxy object needs to be initialized,The load () method may throw a LazyInitializationException.

③ If no corresponding record is queried in the data table and the Session is not closed, get () returns null if the object needs to be used. If load () is used, an exception is thrown.

> Update () changes a free object to a persistent object.

① Update a persistent object without explicitly calling the update () method, because when calling the commit () method of Transaction, the Session flush () will be executed first () method (make the data in the data table consistent with the object state in the Session cache. If they are inconsistent, send the update Statement)

② To update a free object, you must call the update () method of the Session explicitly to change a free object to a persistent object. What is a free object?

  

Note:

① The update statement is sent no matter whether the free object to be updated is consistent with the data table. However, the update statement is not sent if the data is not updated for the Persistent Object. How can we prevent the update () method from blindly sending update statements? Solution: in the class node of the. hbm. xml file, set select-before-update = true (the default value is false, but this attribute is usually not required)

② If no corresponding object exists in the data table, an exception is thrown when the update () method is called.

③ When the update () method is associated with a free object, if a persistence object with the same id attribute exists in the Session cache, an exception (NonUniqueObjectException) is thrown ), that is, two objects with the same id cannot exist in the Session cache.

> SaveOrUpdate () includes both the save () and update () methods.

Execute the update () method on the free object and the save () method on the temporary object. Identify the free object and the temporary object based on the object's id (create an object without setting the id ), IDs are free objects and no IDs are temporary objects.

Note: If the id is not null but there is no corresponding record in the data table, an exception is thrown.

> Delete () method to perform the delete operation

① As long as the id of the object to be deleted corresponds to the id of a record in the data table, both the persistence object and the free objectPreparationDelete

② If the id does not have a corresponding record in the data table, an exception is thrown.

③ Set the Hibernate. use_identifier_rollback attribute of the hibernate configuration file to true. After the object is deleted, the id attribute is set to null.

> The evict () method removes the specified persistent object from the cache.

> To call a stored procedure, you must first obtain the native jdbc api. How can you obtain the Connection object?

@Testpublic void testDoWork(){    session.doWork(new Work() {      @Override      public void execute(Connection connection) throws SQLException {        System.out.println(connection);    }    });}

Iii. Hibernate configuration file

1. Use the c3p0 data source in hibernate

1) Import jar package hibernate-release-4.2.4.Final \ lib \ optional \ c3p0 all

2) Add Configuration

-C3p0. max_size: Maximum number of connections in the database connection pool

-C3p0. min_size: Minimum number of connections in the database connection pool

-C3p0. acquire_increment: number of database connections obtained at the same time when the connection pool in the database is exhausted

-C3p0. timeout: after how long the connection object in the database connection pool has not been used, it should be destroyed.

-C3p0. idle_test_period: indicates how long the connection pool detection thread times out to detect all connected objects in the pool. the connection pool itself does not remove itself from the connection pool. Instead, a thread is dedicated to doing this at a certain interval, this thread compares the time difference between the last used time and the current time of the connected object with timeout to determine whether to destroy the connected object.

-C3p0. max_statements: Number of cached Statement objects

2. Only two configuration items valid for the Oracle database

1) jdbc. fetch_size: set the maximum number of records retrieved from the database each time the JDBC Statement reads data: 100

2) jdbc. batch_size: Set to batch Delete the database. The batch size is the best for batch update and batch insert: 30. For other configuration items, see the official documentation of Hibernate.

/Hibernate-release4.3.11.Final/documentation/manual/en-US/html/index.html

4. Object link ing file *. hbm. xmlNote: Generally, A. hbm. xml file must correspond to only one class.

1. hibernate-mapping is the root element of the hibernate ing file.

> Package (optional): Specifies a package prefix. If the fully qualified class name is not specified in the ing document, this is used as the package name.

2. class

> Name: Specifies the name of the persistent class mapped to this persistent class.

> Table: Specifies the table name mapped to the persistent class. Hibernate uses the Class Name of the persistence class as the table name by default.

> Dyanmic-update: if it is set to true, an update statement is generated dynamically when an object is updated. The update statement only contains all fields whose values need to be updated. The default value is false.

> Dyanmic-insert: if it is set to true, an insert statement is generated dynamically when an object is saved. The insert statement contains only all fields whose values are not null. The default value is false.

> Select-before-update: sets whether to execute a query before Hibernate updates a persistent object. The default value is false.

3. id

> Name: The property name that identifies the persistence class OID

> Column: Specifies the column name of the data table mapped to the identity attribute (name of the primary key field ).

> Unsaved-value: If this attribute is set, Hibernate compares the OID value of the persistence class with this attribute value to identify whether the object of the current persistence class is a temporary object.

4. generator: Set the persistence Class Identifier generator

> Class: Specifies the full-qualified class name or its abbreviated name of the identifier generator used.

> Primary Key Generation Policy:

① The increment identifier generator is assigned a value for the proxy primary key in an incremental manner by Hibernate (not required during development due to concurrency issues)

② The identity identifier generator is used by the underlying database to generate the identifier. It requires the underlying database to define the primary key as the Automatically increasing field type.

③ The sequence identifier generator uses the sequence provided by the underlying database to generate the identifier (not supported by MySQL)

④ The hilo identifier generator is generated by Hibernate based on a high/low algorithm. It obtains the high value from the fields of a specific table in the database.

NativeThe identifier generator uses the identity, sequence, or hilo identifier generator based on the underlying database's support for automatically generated identifiers. (commonly used)

> Property: used to specify the ing between class attributes and table fields.

> Ing derived attributes: Define fields in the corresponding JavaBean, but do not add fields to the data table. Configure the fields in the. hbm. xml file.

<! -- Ing derived Attributes --> <property name = "desc" fornula = "(select concat (author, ':', title) from News n where n. id = id) "> </property>

Test: System. out. print (news. getDesc ());

5. ing Java date and time types

1) Two Basic Knowledge:

① In Java, the types that represent time and date include: java. util. date and java. util. calendar. in addition, three java extensions are provided in the jdbc api. util. subclass of the Date class: java. SQL. date, java. SQL. time and java. SQL. timestamp, which corresponds to the DATE, TIME, and TIMESTAMP types in the standard SQL type respectively.

② In standard SQL, the DATE type indicates the DATE, the TIME type indicates the TIME, and the TIMESTAMP type indicates the TIME stamp (including both the DATE and TIME information ).

2) how to map:

I. because java. util. date is java. SQL. date, java. SQL. time and java. SQL. timestamp parent class, so java. util. date can correspond to DATE, TIME, and TIMESTAMP in the standard SQL type.

II. I-based, so when setting the Date type of the persistence class, set it to java. util. Date.

III. How to map java. util. Date to DATE, TIME, and TIMESTAMP? You can use the type property of property to map data. For example:

<property name="date" type="timestamp">    <column name="DATE" /></property><property name="date" type="data">    <column name="DATE" /></property><property name="date" type="time">    <column name="DATE" /></property>

Timestamp, date, and time are not Java or standard SQL types, but hibernate ing types.

6. hibernate ing for Java large object types (learn more)

1) store binary images

2) Read Binary Images

Note: The available () method of stream can obtain the file size.

7. ing Composition

1) Hibernate classifies persistence attributes into two types:

-Value Type: No OID and cannot be persisted independently. The lifecycle depends on the lifecycle of the object of the persistence class.

-Entity type: it has an OID and can be persisted independently. It has an independent life cycle.

2) ing<Component>To map

Hibernate uses the <component> element to map components. The element table name pay attribute is an integral part of the Worker class, which is called a component in Hibernate (no Id, object classes with Id attributes cannot be mapped using component)

 

Related Article

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.