Getting hibernate --- Summary: The basic configuration and basic ideas ---- complete [the first day]

Hibernate architecture and entry

A, O / R Mapping

Object-relational mapping technology. Using the relationship between objects described association between the database tables. The Java program object is automatically persisted to a relational database.

The relationship between objects in memory:

1. Related

2, inheritance

Object - existing relational mapping form: middleware.

Hibernate solve the problem:

1, solve and reflect on the table is not the same as the primary key column and other columns standing, effective identification records in the database table.

2, address the link between the table and the table, such as one to many, many to one, etc., to solve the association between the primary keys, foreign keys.

Two, Hibernate architecture and start example:

Using the database and configuration data to provide persistence services for the use of the program. Database information stored in the configuration file.

Example 1:

Former follows and writing code, as well as view the configuration of the previous chapter of a specific :( See blog Park: https://www.cnblogs.com/ciscolee/p/10942389.html )

1 , src under the new folder Resource , then the new hibernation.cfg.xml , content:

 

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE the Configuration Hibernate-the PUBLIC 
    "- // Hibernate / Hibernate the Configuration DTD 3.0 // EN" 
    "http://www.hibernate.org/dtd /hibernate-configuration-3.0.dtd " > 
< Hibernate-the configuration > 
<-! profiles tab order * Property, Mapping *, (class-Cache | Collection-Cache), Event, listener * -> 
    < the session-Factory's > 
      <! - the drive set access described mysql database -> 
      < Property name = "connection.driver_class" > com.mysql.jdbc.Driver </ Property >
      <! - set up a database url ->
      < Property name = "connection.url" > jdbc: MySQL: //127.0.0.1: 3306 / the Test </ Property > 
      <-! Specify a login database user accounts -> 
      < Property name = "connection.username" > root </ property > 
      <-! specify the login database user password -> 
      < property name = "connection.password" > 123456 </ property > 
      
      <-! settings to access the database dialect, improve database access performance -> 
      < property name = "dialect" >org.hibernate.dialect.MySQLDialect</property>
      <!-- 设置ddl -->
      <!-- <property name="hbm2ddl.auto">auto</property> -->
        
      <!-- 指出映射文件 -->
      <mapping resource="resource/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 

 

 

2 , src under the new Customer.hbm.xml , a java file class database mapping:

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


<hibernate-mapping package="bean" auto-import="false">
   <!-- POJO类映射表及某表的关系-->
   <class name="bean.Customer" table="customers" catalog="test">
       <id name="customerID" type="java.lang.String">
           <column name="customerID" length="8"/>
           <generator class="assigned"></generator>
       </id>
       <!-- 映射表中name字段 -->
       <property name="name" type="java.lang.String">
          <column name="name" length="40"/>
       </property>
       <!-- 映射表中phone字段 -->
       <property name="phone" type="java.lang.String">
          <column name="phone" length="16"/>
       </property>  
   </class>
</hibernate-mapping>

 

 

 

3 , the new class mapping table:

 

package bean;

public class Customer {
    private String customerID,name,phone;

    public String getCustomerID() {
        return customerID;
    }

    public void setCustomerID(String customerID) {
        this.customerID = customerID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

 

 

 

. 4 , HibernateSessionFactory class operation for the session, i.e. the session database connections stored.

 

package hibernate.factory;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import bean.Customer;

public class HibernateSessionFactory {
    private static String configfile = "resource/hibernate.cfg.xml";
    /**ThreadLocal是一个本地线程**/
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static the Configuration config;
     Private  static the SessionFactory the sessionFactory;
     / ** reading the configuration file, create a session factory, a static block code, the compiler has been run * * / 
    static {
         the try { 
            config = new new the Configuration () Configure (configfile. ); 
            the sessionFactory = config.buildSessionFactory (); 
        } the catch (Exception E) {
             // the TODO: Exception handle 
            e.printStackTrace (); 
        } 
    } 
    / ** open a session through the session factory you can access the database * * / 
    public  static Session getSession(){
        Session session = (Session)threadLocal.get();
        if (session==null||!session.isOpen()) {
            if (sessionFactory==null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory!=null)?sessionFactory.openSession():null;
        }
        return session;
    }
    /**重新创建一个会话工厂**/
    public static void rebuildSessionFactory() {
        try {
            config.configure(configfile);
            sessionFactory = config.buildSessionFactory();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    /**关闭与数据库的会话**/
    public static void closeSession() {
        Session session = (Session)threadLocal.get();
        threadLocal.set(null);
        if (session!=null) {
            session.close();
        }
    }
}

 

 

 

5 , test class:

 

Package the bean; 

Import java.util.List; 

Import hibernate.factory.HibernateSessionFactory; 



Import org.hibernate.Session for;
 Import org.hibernate.query.Query; 

public  class the Test { 
    @SuppressWarnings ( "rawtypes" )
     public  static  void main (String [] args) {
         / ** Create a session by a session session object factory class * * / 
        session session = HibernateSessionFactory.getSession ();
         / ** Create a session by a session object query object * * / 
        query query = session.createQuery ( "from bean.Customer" );
        List list = query.list();
        for (int i = 0; i < list.size(); i++) {
            Customer customer  = (Customer)list.get(i);
            System.out.println(customer.getCustomerID()+customer.getName()+customer.getPhone());
        }
        HibernateSessionFactory.closeSession();
        
    }
}

 

 

 

Three, Hibernate core interface

1, Configuration Interface

Responsible for managing the Hibernate configuration information. To be able to connect to the database must be configured with a number of properties, which comprises:

Database the URL of the database user, database user password, database JDBC driver class, the database dialect , used to provide support for a particular database, which contains an implementation of a particular database feature.

/ * Create a configuration object, reads the configuration file * /

Configuration config = new Configuration();

Config.configure(“resource/hibernate.cfg.xml”);

2、SessionFactory

Use the program to get inside the factory from session session instance, here we use a design pattern, factory pattern.

The user program from the factory class SessionFactory obtain the Session instance. SessionFactory more lightweight than his resources occupied, so he should be able to share in the entire program. A project usually only need a SessionFactory enough, but when the project need to operate more than one database, you must specify a database for each SessionFactory .

Session factory caches generate SQL statements and Hibernate mapping metadata used at runtime. It also contains the unit of work in a data read and can be reused (only classes and will be so designated collection mappings using such secondary cache) later work Session class.

/ ** produced by a session factory configuration object * /

SessionFactory factory = config.buildSessionFactory();

3, Session Interface

The interface is Hibernate the most popular interface. Session is not thread safe, he once operation between representatives of the database. Session is the underlying persistence layer operation, the equivalent JDBC the Connection . However, Hibernate , instantiate the Session is a lightweight class, creation and destruction will not take up a lot of resources. Session by SessionFactory open, after all the work is done and needs to close. But if in the program, constantly being created and destroyed Session object would adversely affect the system, it is sometimes necessary to consider Session of management to create a reasonable, rational destroyed.

/ ** by generating a session factory * /

Session session = factory.openSession();

4, Query class

Use Query class can easily persistence layer and database query object, it can have two ways:

Query using HQL or a local database SQL statements to write.

/ * Generated by the session a query object ** /

Query query = session.createQuery("from bean.Customer");

// by querying the database object query returns a collection of

List list = query.list();

for (int i = 0; i < list.size(); i++) {

Customer customer = (Customer)list.get(i);

System.out.println(customer.getCustomerID()+customer.getName()+customer.getPhone());

5, Transaction Interface

If you increase the data or modify data to the database, you need to use a transaction, then they need the interface.

Transaction interface is an abstraction of the actual transaction implementation, the interface can be achieved JDBC transaction, JTA in the UserTransaction , or even a CORBA across containers of affairs matters. The reason for this design is to allow developers to use a unified operational matters, making their own projects can be easily ported between different environments and containers.

 

Example Two:

**************** example of a configuration file with

Hibernate programming ideas :

 

Package the bean; 


Import java.util.List; 

Import org.hibernate.Session for;
 Import the org.hibernate.SessionFactory;
 Import the org.hibernate.cfg.Configuration;
 Import org.hibernate.query.Query; 

public  class the Hibernate basic programming ideas { 

    public  static  void main (String [] args) {
         / ** Create a configuration object, reads the configuration file * * / 
        String configfile = "Resource / the hibernate.cfg.xml" ; 
        the configuration config = new new the configuration (); 
        config.configure ( configfile); 
        / ** produced by a session configuration object factory class ** / 
        The SessionFactory the sessionFactory = config.buildSessionFactory ();
         / ** generating a session through the session factory class instance * * / 
        the Session the session = sessionFactory.openSession ();
         / ** generated by a session query object Query * * / 
        Query Query = session.createQuery ( "from bean.Customer" );
         / ** query returns a collection * List * / 
        List <the Customer> cuslist = Query.list ();
         for (CuS the Customer: cuslist) { 
            System.out.println ( "ID =" cus.getCustomerID + () + ", name =" cus.getName + () + ", Phone =" + cus.getPhone ()); 
        }
    }
}

 

Finally, summarize, such as reconfiguration, an xml configuration file before, please refer to the document profile dtd into the environment.

Guess you like

Origin www.cnblogs.com/ciscolee/p/10945126.html