[Hibernate] entry

Overview First, Hibernate Framework

1.1 What is Hibernate

  • Frame: semifinished software, complete part of the function code.
  • Hibernate: Hibernate is an object-relational mapping framework for open source, it had a very lightweight JDBC object package so that the programmer using the object can be arbitrary Java programming thinking to manipulate the database. Hibernate can be used in any occasion using JDBC, Java can be used in both client program can also be used in Servlet / JSP Web application, the most revolutionary is, Hibernate can replace EJB CMP in the application of the J2EE architecture to complete the task of data persistence.
  • Hibernate is a persistence layer solutions for lightweight JavaEE applications is a relational database ORM framework.
    • ORM:Object Relational Mapping.
    • The table in Java entity classes and establish a database of maps. Can operate Java objects, so as to operate the database.
  • Common persistence framework
    • Hibernate
    • JPA: JPA Java Persistence API.JPA through JDK 5.0 annotations or XML description of the object - mapping between relational tables (only interface specification)
    • MyBatis: predecessor Ibatis

1.2 Hibernate advantage

  • Hibernate JDBC database access code to make a package, simplifies the data access layer tedious repetitive coding
  • Hibernate is a mainstream jdbc-based persistence framework, is an excellent orm achieve, simplifying the dao layer coding it a large degree of
  • Hibernate uses java reflection mechanism, instead of bytecode classes achieve transparency
  • Hibernate performance is very good, because it is a lightweight frame. Flexibility mapped very well. It supports many relational databases, complex relationships from one-to-many.

Two, Hibernate logging

  • Log: some of the information in the program development.
  • General information Output: System.out.println(“”);
    • Not this way
    • If the output contents are more projects have already been developed, you do not want to use the output. Need to open each class, code comments will be output.
  • Log: Hibernate use slf4j technology.
    • slf4j: SLF4J, namely simple log facade (Simple Logging Facade for Java), not specific logging solution, which only serve a wide variety of system logs.
    • For integration with other systems log.
    • Commonly used in the enterprise logging: log4j
    • Specific logging program.
  • Log4J logging levels:
    • fatal (fatal), error (common mistake), warn (warning), info (information), debug (debug), trace (stack information).
  • Logger.error ( "error message");
  • In the form of the configuration file, an error message appears.
  • Level configuration is info.
  • Log4J three components:

    • Recorder (Loggers is)
      • Format: = logger level output source 1, source 2 output
      • log4j.rootLogger=info, stdout
    • Output source (Appenders)
      • log4j.appender.stdout = org.apache.log4j.ConsoleAppender, console output.
      • log4j.appender.file = org.apache.log4j.FileAppender, output to the file.
    • Layouts (Layouts)
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    

Dependent jar package

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

Three, Hibernate entry procedures

3.1 introduces dependence (5.x version)

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.2.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-c3p0</artifactId>
    <version>5.4.2.Final</version>
</dependency>

3.2 Create a table (relational database)

create table customer(
id int primary key auto_increment,
name varchar(20),
age int
);

3.3 create an entity class

public class Customer {
private int id;
private String name;
private int age;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
}
    

3.4 Creating ORM mapping.

  • Mapping file is an XML format file as long as you can. Any name.
    • Typically Name Authority:
    • Entity class name .hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    
<hibernate-mapping>
    <!-- 建立类与表的映射 -->
    <!-- class标签:用于映射类与表的关系 name :类的全路径  table:表名称 -->
    <class name="com.hao.entity.Customer" table="customer">
        <!-- 建立类中属性与表中的字段映射 -->
        <!-- 唯一标识 -->
        <!-- 使用id的标签 配置唯一属性 -->
        <!-- 在<id>标签中配置一个主键的生成策略. 此处用native 会根据数据库的设置自动选择主键生成策略 -->
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <!-- 普通属性 -->
        <!-- property标签:映射类中的普通属性 name:类中的属性名称, column:表中字段名称 -->
        <!-- 
            type:三种写法
                * Java类型 :java.lang.String
                * Hibernate类型 :string
                * SQL类型 :不能直接使用type属性,需要子标签<column>
                    * <column name="name" sql-type="varchar(20)"/>
         -->
        <property name="name" column="name" type="string"/>
        <property name="age" column="age"/>
    </class>
</hibernate-mapping>
    

3.5 to create a core configuration file.

<hibernate-configuration>
    <session-factory>
        <!-- 必须去配置的属性 -->
        <!-- 配置数据库连接的基本信息:此处引用了mysql-conn 5.8 最新的连接驱动 -->
        <property name="hibernate.connection.driver_class">
            com.mysql.cj.jdbc.Driver
        </property>
        <property name="hibernate.connection.url">
            jdbc:mysql:///test
        </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">rootroot</property>
        <!-- Hibernate的方言 -->
        <!-- 生成底层SQL不同的 -->
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <!-- 可选的属性 -->
        <!-- 显示SQL -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL -->
        <property name="hibernate.format_sql">true</property>
        <!-- hbm:映射 to DDL: create drop alter -->
        <property name="hibernate.hbm2ddl.auto">update</property>
            
        <!-- C3P0连接池设定 -->
        <!-- 使用c3po连接池 配置连接池提供的供应商 5.X版本此处变化了,如下:-->
        <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>

            
        <!--在连接池中可用的数据库连接的最少数目 -->
        <property name="c3p0.min_size">5</property>
        <!--在连接池中所有数据库连接的最大数目 -->
        <property name="c3p0.max_size">20</property>
        <!--设定数据库连接的过期时间,以秒为单位, 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
        <property name="c3p0.timeout">120</property>
        <!--每3000秒检查所有连接池中的空闲连接 以秒为单位 -->
        <property name="c3p0.idle_test_period">3000</property>
            
        <!-- 通知Hibernate加载那些映射文件 ->
        <mapping resource="com/hao/entity/Customer.hbm.xml" />  
    </session-factory>
</hibernate-configuration>
    

Writing tests 3.6

// 向数据库中插入一条记录
@Test
public void demo1(){
    // 1.Hiberante框架加载核心配置文件(有数据库连接信息)
    Configuration configuration = new Configuration().configure();
    // 2.创建一个SessionFactory.(获得Session--相当连接对象)
    SessionFactory sessionFactory = configuration.buildSessionFactory();
    // 3.获得Session对象.
    Session session = sessionFactory.openSession();
    // 4.默认的情况下,事务是不自动提交.
    Transaction tx = session.beginTransaction();
    // 5.业务逻辑操作
    
    // 向数据库中插入一条记录
    Customer customer = new Customer();
    customer.setName("小明");
    customer.setAge(23);
    
    session.save(customer);
    
    // 6.事务提交
    tx.commit();
    // 7.释放资源
    session.close();
    sessionFactory.close();
}

Four, CRUD operations

4.1 record keeping:

session.save(customer);

4.2 query based on the primary key:

Customer customer = (Customer)session.get(Customer.class ,1);
Customer customer = (Customer)session.load(Customer.class,1);
  • get and load difference :( interview questions)

  • 1. Send SQL time:

    • This method uses a load technical delay .lazy loading (lazy loading). actually using the data when the object. (data object does not include the primary key).
    • get this way is immediately retrieved. When the execution session.get () method, immediately send SQL statements to query.
  • 2. Return of objects:

    • load method returns a proxy object.
    • get method returns true object.
  • 3. query data that does not exist:

    • load method Throws: ObjectNotFoundException (throws this exception).
    • get methods throw an exception:. NullPointException (now there is no exception thrown)

4.3 modify records

session.update(customer);
修改有两种方式 :
// 5.1手动创建对象的方式
Customer customer = new Customer();
customer.setId(2);
customer.setName("小明");
    
session.update(customer);
***** 这种方式如果没有设置的属性,将这个属性的默认值存入了.(不推荐使用.)
    
// 5.2先查询在修改的方式(推荐方式)
Customer customer = (Customer) session.get(Customer.class, 1);
customer.setName("小李");
    
session.update(customer);

4.4 Delete Record

session.delete(customer);
//删除记录有两种方式:
// 5.1手动创建对象的方式
Customer customer = new Customer();
customer.setId(2);
session.delete(customer);
    
// 5.2先查询在删除的方式
Customer customer = (Customer)session.get(Customer.class, 1);
session.delete(customer);

4.5 All inquiries

//1. HQL:
// HQL:Hibernate Query Language.
// 面向对象的写法:
Query query = session.createQuery("from Customer where name = ?");
query.setParameter(0, "小明");
Query.list();
    
//2. QBC: Query By Criteria.(条件查询)
//此方法已经过时
Criteria criteria = session.createCriteria(Customer.class);
criteria.add(Restrictions.eq("name", "小李"));
List<Customer> list = criteria.list();
    
//3. SQL //这里用的5.x的版本,与原来的3.x版本不同
NativeQuery query = session.createSQLQuery("select * from customer");
List<Object[]> list = query.list(); // 每一个数组就是一条记录
    
NativeQuery query = session.createSQLQuery("select * from customer");
query.addEntity(Customer.class); //这里添加一个实体,list方法返回的就是一个Customer的集合,上面的那种方式返回的是一个Object数组的集合,
List<Customer> list = query.list();

Five, Hibernate common configuration and core API

A common configuration of 5.1 Hibernate

1. Core Configuration

  • Core Configuration There are two ways to configure:
  • 1. The configuration properties file
    * the hibernate.properties
    * Format:
    * = value Key
    * = com.mysql.jdbc.Driver hibernate.connection.driver_class

    • Note: There is no way to load the mapping file in the core configuration file (. Must be manually coded way to load .)
  • 2.XML configuration file format:

    • hibernate.cfg.xml
    • format:
      <property name="hibernate.connection.username">root</property>

    • In the core configuration

    • 1. Must configurations:

      • Database connected four basic parameters:
      hibernate.connection.driver_class  连接数据库驱动程序
      hibernate.connection.url   连接数据库URL
      hibernate.connection.username 数据库用户名
      hibernate.connection.password 数据库密码
      • Hibernate dialect:
      hibernate.dialect   操作数据库方言
      
    • 2. Optional configurations

    hibernate.show_sql  true 在控制台上输出SQL语句
    hibernate.format_sql  true  格式化控制台输出的SQL语句
    hibernate.connection.autocommit true 事务是否自动提交
    hibernate.hbm2ddl.auto create/create-drop/update/validate
    * create : 每次执行的时候,创建一个新的表.(如果以前有该表,将该表删除重新创建.) 一般测试的时候的使用.
    * create-drop : 每次执行的时候,创建一个新的表,程序执行结束后将这个表,删除掉了. 一般测试的时候使用.
    * update : 如果数据库中没有表,创建一个新的表,如果有了,直接使用这个表.可以更新表的结构.
    * validate : 会使用原有的表.完成校验.校验映射文件与表中配置的字段是否一致.不一致报错.
    • 3. Mapping configuration:
    • Loading map file in the core configuration file:
    <mapping resource="cn/itcast/hibernate3/demo1/Customer.hbm.xml" />
    

2. Mapping configuration file

  • ORM: the object and relational mapping.
  • Configuring Java object mapping table.
  • Configuration class mapping table
name:类的全路径:
table:表的名称:(可以省略的.使用类的名称作为表名.如果类名为Order时,由于order为数据库的关键字,所以此时是不能创建表的);
<!-- 如果为Order table应写为orders-->
<class name="com.hao.entity.Order" table=”orders”>
  • ☆☆ arranged with common attributes field mappings ☆☆ : Get Class name to see the inside, see column to find a table inside the database
<property name="name" column="name" type="string" length=”20”/>
  • Which type Three Kind of Writing

  • Java type: java.lang.String

  • Hibernate type: string

  • SQL types: type attribute can not be used directly, need sub-tab

<property name="name" column="name" length="20">
    <column name="name" sql-type="varchar(20)"></column>
</property>    
  • ☆☆ configuration map uniquely identifies the primary key ☆☆

    • A primary key table is only one form:
    <id name="id" column="id">
        <generator class="native"/>
    </id>
    • Generation strategy sequence, identity, increment, assigned, uuid / hilo, native
    • A table form corresponding to the plurality of primary keys :) :( composite primary key (entity class must implement the serialization interface) --- understanding.
    <composite-id></composite-id>
    
  • connection relation

  • Named SQL

<query name="findAll">
    from Customer
</query>
<sql-query name="sqlFindAll">
    select * from customer
</sql-query>

Sixth, the core API

6.1 Configuration

  • Hibernate is responsible for managing the configuration information

Load core profile

  • There are two core configuration:
  • 1.hibernate.properties loading as follows:
Configuration configuration = new Configuration();
  • 2.hibernate.cfg.xml loading as follows:
Configuration configuration = new Configuration().configure();

Loading map file:

a. mapping file configuration in the core profile
b. Manually loading method of mapping file

// 第一种写法:
configuration.addResource("com/hao/entity/Customer.hbm.xml");
//第二种写法:(要求:映射文件名称要规范,类与映射在同一个包下)
configuration.addClass(Customer.class);

6.2 SessionFactory (Session factory)

  • ConfigurationObject generation based on the current configuration information SessionFactoryobjects
  • SessionFactory Objects stored in the current database configuration information and all of the mappings and predefined SQL statements
  • SessionFactory Objects are thread-safe
  • SessionFactoryHe is also responsible for maintenance Hibernateof secondary cache
  • SessionFactoryObjects based on database information, maintain the connection pool is created Session(the equivalent of Connection) objects.

  • Extraction Tools

public class HibernateUtils {
    private static Configuration configuration;
    private static SessionFactory sessionFactory;
    
    static{
        configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
    }
    
    public static Session openSession(){
        return sessionFactory.openSession();
    }
    
    public static void main(String[] args) {
        openSession();
    }
}

6.3 Session

  • The equivalent JDBCofConnection
  • SessionThe object is a single-threaded interaction between the application and the database, is Hibernatethe center of operations
  • SessionIt is not thread safe
  • All persistent object must sessiononly be carried out under the management of persistence operations
  • SessionAn object has a cache explicitly performed flushbefore, all operations are persistent data cache sessionat the object
  • Persistent classes and Sessionafter the associate has the ability to persistence
  • SessionIt maintains Hiberantea cache .
Session session = HibernateUtils.openSession();
session.save()/persist()      //添加.
session.update()           //修改
session.saveOrUpdate()    //增加和修改对象
session.delete()         //删除对象
session.get()/load()    //根据主键查询
session.createQuery()    //创建一个Query接口,编写HQL语句
session.createSQLQuery()    //创建一个SQLQuery接口,编写SQL语句数据库操作对象
session.createCriteria()    //返回一个Criteria接口.条件查询

6.4 Transaction

Transaction tx = session.beginTransaction();
  • Common method Affairs
commit()        //提交相关联的session实例
rollback()      //撤销事务操作
wasCommitted()  //检查事务是否提交
  • If the transaction is not turned on, then each Session of the operation, are the equivalent of a separate transaction

6.5 Query

  • Query on behalf of a Hibernate object-oriented query operation
  • session.createQuery accept a HQL statement
  • Hibernate Query Language HQL is an abbreviation, like syntax SQL syntax, but fully object-oriented

6.6 Criteria

  • Criteria query conditions

Seven, Hibernate persistent classes in

  • Persistent class: + entity class mapping file.
  • Persistent class is the preparation of specifications:
  • A parameter-free public access specifier constructor: use reflection.
  • Providing an identity attribute, table mapping data primary key field:
    • java distinguish between two objects is the same whether a use -> Address.
    • Distinguishing two records are consistent database: using -> primary key.
    • Hibernate persistence distinguish whether the object is the same -> According to uniquely identify:
  • All properties provide public access control method breaks set get: the value stored in the frame when the use and value.

    • Identifying attributes basic data types should be used type of packaging
    • Using basic data types:
    • Results table:
      Student ID Name grades
      1 Joe Smith null
    • Try not to use persistent class final modified:
      • With a final modified class it can not be inherited. Can not generate the proxy object. (Time delay loading of return proxies. Lazy loading will fail.)
  • When construction of the table:

  • Natural primary key and a surrogate primary key:

  • Natural primary key:

  • Create a person table staff table a record uniquely determined. I have the identity card number. We can use the ID number as the primary key. (ID number itself is a property of personnel as the primary key.)

  • Acting Primary key:

  • Create a person table. Table art uniquely identify a record, but the ID number is not used as the primary key, the new field (with a new field as the primary key. Identifies a role only.)

  • To try to maintain their own Hibernate primary key

  • Generation Strategy ☆☆ ☆☆ primary key

  • increment : Automatic growth for short int long ... instead of using the automatic growth mechanism of the database using the automatic growth Hibernate framework...

    • select max(id) from 表;
    • +1 on the basis of the maximum value. (Multithreading problems.) Do not use in a cluster
  • identity : Automatic growth for short int long ... automatic database growth mechanism is not suitable for the Oracle database..

  • sequence : Sequence applies to short int long ... applications on Oracle.

  • uuid : For primary key of type String random character string as a primary key.

  • native: Local policy different underlying database automatically select the appropriate identity or sequence..

  • assigned : Hibernate primary key frame is not maintained, the primary key generated automatically by the program.

  • foreign : The primary key foreign (application in multi-table one to one relationship.)

Guess you like

Origin www.cnblogs.com/haoworld/p/hibernate-ru-men.html