An article let you immediately Hibernate entry

In front of us finished school Struts2, then we will go to learn the second frame Hibernate.
What is Hibernate?
Hibernate object-relational mapping framework is an open source, it had a very lightweight JDBC object package, it will POJO mapping relationship with a database table, is a fully automated ORM frameworks, Hibernate automatically generates SQL statements, automatically, so that Java programmers can use arbitrary object 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.
By the way tell us about what is ORM.
ORM: Object-relational mapping is a programming technique, is simply our program entity classes and database tables set up correspondence.
Why have object-relational mapping it?
Hypothetically, when you're developing an application, you might write a lot of code data access layer, from the database to save, delete, read object information and so on. You write in DAO in a lot of ways to read the object data, changing the state of the object, and so on task, and many of these codes are repetitive.
Object's mapping program gives a powerful capability that allows developers to simply grasp the object-oriented thinking to manipulate the database, that is, for a mapping between relational databases and business entity objects, so that we operate in a specific business objects when We do not need to go and deal with complex SQL statements, as long as usual operation object as it can operate up.

HelloWorld

Some basic knowledge of Hibernate after complete understanding, we have to prepare a project Hibernate entry.
First, we have to write hibernate configuration file, the new file hibernate.cfg.xml in the src directory:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 配置连接数据库的基本信息 -->
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///test</property>

        <!-- 配置hibernate的基本信息 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- 执行操作时是否在控制台打印sql -->
        <property name="show_sql">true</property>

        <!-- 是否对sql进行格式化 -->
        <property name="format_sql">true</property>

        <!-- 指定自动生成数据表的策略 -->
        <property name="hbm2ddl.auto">update</property>

        <!-- 指定关联的.hbm.xml文件 -->
        <mapping
            resource="com/itcast/hibernate/helloworld/Account.hbm.xml" />
    </session-factory>
</hibernate-configuration>

There is some relevant configuration information.
Then we create a class Bean Account:

package com.itcast.hibernate.helloworld;

public class Account {

    private Integer id;
    private String name;
    private double money;

    public Account() {

    }

    public Account(String name, double money) {
        this.name = name;
        this.money = money;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
    }
}

Next we need to create a profile object-relational mapping, the new Account.hbm.xml files in the directory with the same level of the class:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- 使Account类对应数据表ACCOUNT -->
    <class name="com.itcast.hibernate.helloworld.Account" table="ACCOUNT">
        <!-- id标签中的name为类中的属性名;colum标签中的name为数据表中的列名 -->
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <!-- 指定主键的生成方式  native:使用数据库本地的方式-->
            <generator class="native" />
        </id>
        <!-- property表示非id的其它列 -->
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="money" type="double">
            <column name="MONEY" />
        </property>
    </class>
</hibernate-mapping>

Simply disposed about the profile type and that the object is a mapping table.
Then we write about the test code:

        // 1、创建一个SessionFactory对象
        SessionFactory sessionFactory = null;
        // 1)、创建Configuration对象:对应hibernate的基本配置信息和对象关系映射信息
        // 默认关联的是hibernate.hbm.xml文件,如果你的配置文件名是hibernate.hbm.xml,使用无参构造即可
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        // 2、创建一个Session对象
        Session session = sessionFactory.openSession();
        // 3、开启事务
        Transaction transaction = session.beginTransaction();
        // 4、执行保存操作
        Account account = new Account("张三",1000);
        session.save(account);
        // 5、提交事务
        transaction.commit();
        // 6、关闭Session
        session.close();
        // 7、关闭SessionFactory
        sessionFactory.close();

And then run the test code, hibernate will save data to the database, if you do not have this table, hibernate will automatically help us create a good table and then insert data.
Because hibernate version of the problem, so there will be a lot of pit specifically reported what went wrong we can solve their own Baidu. Hibernate here is my version of 5.X.

+----+------+-------+
| ID | NAME | MONEY |
+----+------+-------+
|  1 | 张三 |  1000 |
+----+------+-------+
1 row in set (0.00 sec)

Then create a persistent class when the need to pay attention to the following questions:

  • You must provide a non-argument constructor
    because Hibernate required Constructor.newInstance () to instantiate a persistent class
  • Identifying a property
    typically mapped to data primary key field of the table, if the attribute is not, some of the functions will not work
  • Persistent class field declared for the class of access methods
  • Non-final classes use
    generated at runtime proxy is an important feature of Hibernate, if the persistent class does not implement any interfaces, Hibernate will use CGLIB generate proxy, if the class is final, you can not generate the proxy CGLIB
  • Equals and hashCode method rewrite
    if necessary the instance of the class into persistent Set (when required for association mapping), these two methods should be overridden

Getting started on the preparation of the cases we finished, I believe the two profiles of the configuration information that everyone can understand that comment is also written very clearly, what about some test code class API, here are brief.

  1. Configuration:
    Configuration Configuration information class is responsible Hibernate, comprising the following:
    the underlying information Hibernate run: the database URL, user name, password, JDBC driver class, the Dialect database, database connection pools (corresponding to hibernate.cfg.xml file)
    Creating Configuration of two ways:
    properties file (hibernate.properties):
    Configuration cfg = new new Configuration ();
    the Xml file (the hibernate.cfg.xml)
    Configuration cfg = new new Configuration () configure ();.
    Configuration of configure method supports with reference access:
    file file = new new file ( "filename");
    the Configuration cfg = new new the Configuration () the configure (file);.
  2. SessionFactory:
    for a single database mapping relationship through memory mirroring compiled, are thread-safe
    SessionFactory object once construction is completed, namely impart specific configuration information
    SessionFactory Session of the production plant
    construction SessionFactory is resource-consuming, under normal circumstances only one application a SessionFactory object initialization
  3. The Session:
    the Session is a single-threaded objects and interactions between the application and the database, Hibernate is the center of operations, all persistent objects must persist before they can be operated at a session of the management. The life cycle of this object is very short. Session object has a cache, the flush until explicitly performed, all data persistence layer operations are cached in the session object, corresponds to the JDBC Connection
  4. Transaction:
    Transaction, learned of the database should all understand, is not repeated

Update

Mentioned above, the data is inserted, then talk about how to use the hibernate here to complete the update operation.

  • session.save (obj); [save an object]
  • session.update (obj);} [update an object
  • session.saveOrUpdate (obj); [a] method of preserving or update
    is not set the primary key, the save;
    has set the primary key, perform the update operation;
    If no primary key exists given!
        SessionFactory sessionFactory = null;
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Account account = session.get(Account.class, 1);
        account.setMoney(2000);
        session.update(account);
        transaction.commit();
        session.close();
        sessionFactory.close();

Run and then query the database:

+----+------+-------+
| ID | NAME | MONEY |
+----+------+-------+
|  1 | 张三 |  2000 |
+----+------+-------+
1 row in set (0.00 sec)

Inquire

Next is the query.

        SessionFactory sessionFactory = null;
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Account account = session.load(Account.class, 1);
        System.out.println(account);
        transaction.commit();
        session.close();
        sessionFactory.close();

operation result:
Here Insert Picture Description

delete

The last is deleted.

        SessionFactory sessionFactory = null;
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Account account = session.get(Account.class, 1);
        session.delete(account);
        transaction.commit();
        session.close();
        sessionFactory.close();

operation result:

mysql> select * from account;
Empty set (0.00 sec)

to sum up

About CRUD operation is very simple, so long as one can be on the other, because the truth is the same. Of course on the use of far more than such a point hibernate function, but this article just to get you started as quickly as possible, so some of the more advanced features in the Advanced I intend to write in.

Guess you like

Origin www.cnblogs.com/blizzawang/p/11411611.html