The Construction of the First Program of Hibernate Learning Notes 1

Keywords: Hibernate Session Database JDBC

Hibernate Learning Notes: Building the First Program

Some time ago, I had a little understanding of Struts 2 framework. I was very happy to learn Hibernate framework myself. This blog post will record the process of building the first Hibernate program. In fact, sometimes I feel that no matter what language or framework we learn, the first HelloWorld program is really very important. If we can't run out of the first HelloWorld program, it will completely affect our interest and motivation in new contacts. However, often the first program will involve a lot of configuration, so it makes it possible for us to use the first HelloWorld program. For beginners to explore a certain period of time, for me, because I do not know what library files to add when I first started learning the framework of Hibernate, so I need to refer to some blogs and videos to better complete the construction of the first program, only after we successfully built the first program, we will be for us. Ready for the later study, in the latter study, we do not need to worry about what library files to add, what configuration is needed? Wait a minute. This blog post is about all the processes of building Hibernate's first program. I hope it will be helpful for you who have just learned Hibernate.

Don't talk too much nonsense, start doing business.

Construction of the first Hibernate program

I believe that you must have learned Java before learning Hibernate, so there must be a Java compiler environment and our common IDE, that is, you must have used eclipse/MyEclipse and other IDEs, if not, you need to download.

Let's assume you have a Java-related development environment (JDK,IDE).

Before introducing, we first provide a reference document: Hibernate 3.1.2 Online Chinese Help Document, which has a good reference value, and also the first Hibernate application building process: http://www.jq-school.com/Show.aspx?id=321 . My first Hibernate building is also completed mainly referring to this document.

1. Preparations

a. Download the Hibernate distribution package on Hibernate's official website and link it as follows: http://hibernate.org/orm/downloads/ After downloading, extract it into the corresponding folder, and some of the Jar packages involved in it will be used by us. I downloaded it with ibernate-release-5.1.0.Final This version.

b. The database driver package, JDBC Driver, depends on the database you use, which is usually available on the official database website. Hibernate supports commonly used databases such as MySQL, Oracle, PostgreSQL, and MS-SQL Server. These databases all have JDBC Driver:

I downloaded my own MySQL database Driver.

Oracle JDBC Driver Download Address (Oracle Protocol must be agreed before downloading)
http://otn.oracle.com/software/htdocs/distlic.html?/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.html

MySQL JDBC Driver Download Address
http://dev.mysql.com/downloads/connector/j/3.0.html

PostgreSQL JDBC Driver Download Address
http://jdbc.postgresql.org/download.html

MS-SQL Server JDBC Driver Download Address
http://www.microsoft.com/downloads/details.aspx?FamilyID=9f1874b6-f8e1-4bd6-947c-0fc5bf05bf71&displaylang=en

2. New project, add Jar package

1) My IDE is MyEclipse. Open MyEclipse and create a new Java Project. My project here is called HelloWorld_Hibernate, and then add the corresponding Jar package.

How do I add Jar packages?

There are two main ways to add Jar packages. The first way is to click on the item --> Build Path --> Add External JARS. Because hibernate has many Jars to add, and these Jar packages belong to hibernate, so we put them together and then introduce them into the project. This is the second method.

The specific steps are as follows:

Windows - > Java - > Build Path - > User Libraries - > new, so that a new folder (my new folder here is: hibernate), and then in this folder, click Add External JARS to add the Jar package, the need to add the Jar package in the hibernate decompressed lib/required, I will add all the packages under this folder. Detailed screenshots are as follows:

When the above steps are completed, we can introduce this into the project.

Entity class Student

There are several attributes in the entity class: id name age and get/set methods for these attributes.

package com.hibernate.model;
    public class Student {
    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;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

All persistent classes require constructors with or without parameters, because Hibernate must use Java reflection mechanisms to create objects for you. The access level of a constructor can be private, but when generating a runtime proxy, access control at least at the package level is required.

Create tables and entity classes in the database

Here we create tables by ourselves, and we can also ask Hibernate to create tables for us.  
In the configuration file hibernate.cfg.xml which will be introduced below:

<! - Attribute hbm2ddl.auto optional values are: create|update|drop-create|invalide 
        Create will create a new table for you every time, so there is data loss.
        update When you add or delete other attributes in your entity class, the corresponding table structure will change, so the table structure will change.
        invalide is the check of object relational mapping.
        -->
<property name="hbm2ddl.auto">create</property> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Hibernate configuration hibernate.cfg.xml configuration file

Hibernate's configuration file is called hibernate.cfg.xml. Don't change the name. If we don't understand Hibernate's principle, it's just asking for trouble.

The contents are as follows, mainly referring to the reference documents mentioned above, and then making some changes.

<?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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>  <!--  hibernate For database name -->
        <!--  User name and password of database -->
        <property name="connection.username">root</property>
        <property name="connection.password">123456789</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect It depends on what kind of database you use. -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
       <!-- <property name="hbm2ddl.auto">create</property> --> 
        <!-- Student Class and table Student The mapping relation of -->
        <mapping resource="com/hibernate/model/Student.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

create mapping file

Although we have established database tables of entity classes above, we have not yet established an association, that is, mapping.

The basic structure of a mapping file looks like this:

<?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>
    [...]
    </hibernate-mapping>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

In our project, the mapping file Student.hbm.xml is as follows:

<?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 package="com.hibernate.model">
    <class name= "Student" table= "Student"> <! -- If we don't write a table, the default table name is the same as the class name - >
        <! - Primary key - >
        <id name="id" column="id">
            <! - Generation Strategy of Primary Key
            <generator class="native"/>
        </id>
        <! -- Other attributes, name corresponds to the attributes of entity classes, column corresponds to the columns of relational database tables - >
        <property name="name"  column="name"/>
        <property name="age"/>
    </class>
    </hibernate-mapping>

    <! - This associates the Student class with the table Student - >.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Test class

After the above work is completed, we can build a test class to test. The code for the test class StudentTest is as follows:

package com.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.model.Student;

public class TestStudent {

    public static void main(String[] args) {
        Student s=new Student();        
        s.setId(1);
        s.setName("wu");
        s.setAge(19);
        //Here's the code in a fixed format, that is, get Session first, and then skip Session's save method.
        Configuration cfg=new Configuration();
        SessionFactory sf=cfg.configure().buildSessionFactory();
        Session session=sf.openSession();
        session.beginTransaction();
        session.save(s);
        session.getTransaction().commit();
        session.close();
        sf.close();
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

The test results in the database are as follows:

This shows that our first Hibernate program succeeded.

Use Annotation to create the first program

The above method uses xml configuration file to create the corresponding relationship between entity classes and database tables. Next, we use Annotation to create the first program.

Next we create an entity class Teacher.

The contents are as follows:

package com.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Teacher {
    private int id;
    private String name;
    private String title;
    @Id
    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 String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

From the above code, you can see annotations like @Entity/@Id, which means that we don't need to write mapping files for entity classes and database tables.

The contents of the hibernate.cfg.xml file are as follows, which differs from the first method by adding such a line of code:

<mapping class="com.hibernate.model.Teacher"/>
  • 1

Details are as follows:

<?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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>  <!--  hibernate For database name -->
        <!--  User name and password of database -->
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect It depends on what kind of database you use. -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
       <!-- <property name="hbm2ddl.auto">create</property> --> 
        <!-- Student Class and table Student The mapping relation of -->
        <mapping resource="com/hibernate/model/Student.hbm.xml"/>

        <mapping class="com.hibernate.model.Teacher"/>

    </session-factory>

</hibernate-configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

The test file is the same as Test Student, as follows:

package com.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.model.Teacher;

public class TestTeacher {

    public static void main(String[] args)  throws Exception{
        Teacher t=new Teacher();
        t.setId(1);
        t.setName("wuranghao");
        t.setTitle("professior");

        Configuration cfg=new Configuration();
        SessionFactory sf=cfg.configure().buildSessionFactory();
        Session session=sf.openSession();
        session.beginTransaction();
        session.save(t);
        session.getTransaction().commit();
        session.close();
        sf.close();
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

Similarly, when we run, the query results in the database table are as follows:

Reference material

1,blog :http://blog.csdn.net/doodoofish/article/details/43207/

2,http://www.jq-school.com/hibernate/html/tutorial.html#tutorial-firstapp


from: http://blog.csdn.net/u010412719/article/details/51258691


Posted by infratl on Tue, 21 May 2019 14:37:50 -0700