Hibernate Framework Foundation--hibernate API and Hibernate master configuration file

Source: Internet
Author: User

Learning Roadmap for Hibernate

Hibernate API Introduction Configuration

the configuration class is responsible for managing Hibernate profile information , including the following:

    1. Hibernate runs the underlying information: database URL, user name, password, JDBC driver class, database dialect, database connection pool, etc. (corresponding to Hibernate.cfg.xml file).
    2. The mapping of the persisted class to the data table (*.hbm.xml file).

There are two ways to create a configuration:

    1. Properties file (hibernate.properties)

       configuration cfg = new 
       Configuration ();     
    2. XML file (hibernate.cfg.xml)

      • Load default configuration file (hibernate.cfg.xml)

        configuration cfg = new configuration (). Configure ();     
      • Or load the configuration file with the specified name

         Configuration cfg = new configuration () .configure ("Myhibernate.cfg.xml")     

The configuration class also has the following common methods:

    • AddResource (String Resource): Imports a mapping file at a specified location.
    • AddClass (class Clazz): Imports a mapping file with a class name prefixed with a specified similarity in a package, with a suffix of. Hbm.xml.
    • Buildsessionfactory (): Create Session factory.
Sessionfactory

A configuration object generates a Sessionfactory object based on the current configuration information. Once the Sessionfactory object is constructed, it is given specific configuration information (the Sessionfactory object holds the current database configuration information and all mappings and predefined SQL statements.) Sessionfactory is also responsible for maintaining Hibernate's Level two cache). The relevant code is as follows:

Configuration cfg = new Configuration().configure();SessionFactory sessionFactory = cfg.buildSessionFactory();

    1. Sessionfactory is thread-safe.
    2. Sessionfactory is the factory that generated the session:

      Session session = sessionFactory.openSession();
    3. Construction sessionfactory consumes resources, and in general, only one Sessionfactory object is initialized in an application.

The Sessionfactory class also has the following two methods:

    • getcurrentsession (), which will be highlighted later.
    • Close (), know just fine.
Session

A session is a single-threaded object that interacts between an application and a database and is the center of hibernate operations, and all persistent objects must be managed by the session to be persisted. This object has a short life cycle. There is a cache in the session, and until the flush () method is explicitly executed, all persisted layer operations are slowed to the presence of the session object. (equivalent to connection in JDBC)

    • Persistent classes have the ability to persist after they are associated with the session.
    • The session is not thread-safe.
    • Some methods of the session class:
      • Methods for getting persisted objects: get (), load ()
      • Persisted objects are saved, updated, and deleted: Save (object), update (object), delete (object)
      • Methods of querying:createquery (String),Createcriteria (Class)
      • Methods for managing transactions: BeginTransaction (), Gettransaction () (Gets the associated transaction object in the current session)
      • Methods for managing Sessions: IsOpen (), flush (), clear (), evict (), close (), and so on.
Transaction
    • Represents an atomic operation, which has the concept of a database transaction. All persistence tiers should be under transaction management, even read-only operations.

      Transaction tx = session.beginTransaction();
    • Common methods:
      • Commit (): submits the associated session instance.
      • Rollback (): Undo transaction operation.
      • Wascommitted (): Checks whether the transaction is committed.
Query and Criteria Interface

is the query interface, the query instance wraps the HQL query statement, HQL is object-oriented, he refers to the class name and the class's property name, not the table name and the field name. The criteria interface completely encapsulates a query statement based on a string, which is more object-oriented than the query interface and is adept at executing dynamic queries.
The query interface has the following common methods:

    • List (): Queries a result set.
    • Uniqueresult (): Queries for a unique result, returns null if there is no result, and throws an exception if there are multiple results.

The method in the criteria interface, which we'll explain later.
For example, to query all the records in the user table in the database, there are 2 ways:

      • Method One: Use the HQL statement

        List<User> list = session.createQuery("FROM User").list(); // 使用HQL查询

    • Method Two: Use criteria query

      Criteria criteria = session.createCriteria(User.class);List<User> list = criteria.list();

There are also 2 ways to query the information of a user with ID 5:

  • Method One: Use the HQL statement

    List<User> list = session.createQuery("FROM User WHERE id=5").list(); // 使用HQL查询
  • Method Two: Use criteria query

    = session.createCriteria(User.class);// 增加过滤条件criteria.add(Restrictions.eq("id", 5)); // id=5的条件List<User> list = criteria.list();

If you want to query all user information and sort in ascending order in the ID column, the same:

    • Way One: Use HQL statements

      list<user> list = Session.createquery ( From the User ORDER by id). list ();
       //use HQL query       
    • Mode two: Use criteria query

       Criteria = Session.createcriteria (User;//Add sorting criteria criteria.addorder (Order.ASC (" id ")) ; list<user> list = Criteria.list ()    
Hibernate's Running Process

Hibernate is run as follows:

    1. The application first calls the configuration class, which reads the information from the Hibernate configuration file and the mapping file.
    2. Use this information to generate a Sessionfactory object.
    3. A Session object is then generated from the Sessionfactory object.
    4. The transaction object is generated using the Session object.
      • PO can be loaded, saved, updated, deleted, and so on by means of the get (), load (), save (), update (), delete (), and Saveorupdate () of the Session object.
      • In the case of a query, a query object can be generated from the session object and then executed using the Queries object, and if there is no exception, the transaction object submits these operations to the database.

A graph means:

Hibernate master configuration file

Hibernate in front of key configured in Hibernate Master Profile--hibernate.cfg.xml . The prefix may or may not be available. Such as:

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

Equivalent to:

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

The contents of the Hibernate master configuration file (Hibernate.cfg.xml) can be divided into three categories by function:

  • Database information, including the URL of the database, user name, password, JDBC driver class, and database dialect.

    <PropertyName="Hibernate.dialect" >org.hibernate.dialect.mysqldialect</Property><PropertyName= "Connection.url" >jdbc:mysql:///hibernate_20160926</property><property name= "Connection.driver_class" >com.mysql.jdbc.Driver< Span class= "Hljs-tag" ></property>< property name= " Connection.username ">root</property> <property name=  "Hibernate.connection.password" >root</ PROPERTY>             
  • Import the mapping file, such as:

    <mapping resource="cn/itcast/a_helloworld/User.hbm.xml" />
  • Other configurations are:

    • To display the generated SQL statement:

      <property name="hibernate.show_sql">true</property>
    • To format the generated SQL statement:

      <property name="hibernate.format_sql">true</property>
    • Automatically generate table structure:

      <property name="hbm2ddl.auto">create/update/create-drop/validate</property>

Now we focus on the auto-generated table structure statements in other configurations of the Hibernate master configuration file, and the value of key Hbm2ddl.auto can have the following values:

    • Create: Delete before creating.
    • Update: If the table does not exist, it is created, not the same as the update, just do nothing (development time). Note that update is only valid when the information is added, and the change is generally invalid .
    • Create-drop: When the table is initially created (deleted, then created), the sessionfactory executes the close () method when the table is dropped (to invoke the close () method, otherwise the delete operation is not done).
    • Validate: Verify that the table structure is consistent with HBM and throws an exception if it is not consistent.

As long as we configure the table structure statement automatically on the Hibernate master configuration file, the Hibernate framework gets the data definition language (DDL) based on the mapping file to create the table.
In addition to this approach, there is another way to create a table structure, which is to use the Schemaexport tool class.

public class CreateSchema {    // 根据配置生成表结构    @Test    public void test() { Configuration cfg = new Configuration().configure(); SchemaExport schemaExport = new SchemaExport(cfg); // 第一个参数script的作用: print the DDL to the console // 第二个参数export的作用: export the script to the database schemaExport.create(true, true); }}

When you run the test () method, a build table statement similar to the following is printed in the Eclipse console:

drop table if exists t_usercreate table t_user ( id integer not null auto_increment, name varchar(20), primary key (id))

Note: Only tables can be built using either of these methods , and libraries cannot be built .

(GO) Hibernate Framework Foundation--hibernate API and Hibernate master configuration file

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.