[entry level] Hibernate environment construction

[idea2020.1.1]
hibernate is a framework applied in the DAO layer. The functions of DBUtils used before are similar
[distinction – > Java EE's three-tier architecture and MVC idea:
Java EE three-tier structure: web layer, service layer and dao layer;
MVC idea m: model, v: view, c: controller]

Find jar package

jar package acquisition: http://hibernate.org/orm/releases/

I use hibernate 5 two
[link: https://pan.baidu.com/s/1-OzVeT-6JDIYMy2ab3alXg
Extraction code: gsjz]
Get it on the website: take 5.5 as an example
step1:

Step 2: after entering, slide down and select the version you want to download

The downloaded file is in the form of a compressed package. Unpack it and open it

Under the required folder is the jar package required by hibernate.

New Java Web project

In fact, this step should be the first step, but it's not a big problem
https://blog.csdn.net/qq_44641943/article/details/118379496
This is my step in building the project

Import the jar package into the project

step1
Create two new folders under WEB-INF. classes is used to store the generated class files and lib is used to store the jar packages that the project depends on (strictly speaking, the jar packages required for this module)
[only ordinary folders are created]

step2
After copying the jar packages required for hibernate and database connection to the lib folder,



After selecting lib, this line will appear, and select – > apply

You can see the imported jar package as shown in the figure below

The classes folder is as follows, just Apply

New entity class

When creating a new JavaBean, don't forget the setter and getter methods
(cid actually corresponds to primary key)

Create mapping files for entity classes and database tables

When using hibernate, you do not need to create tables manually. Hibernate helps you create tables. How do you create tables? A: use the configuration file to complete the one-to-one correspondence (mapping) between the configuration entity class and the database table.
The configuration file is in xml format. The xml format file cannot be found in new in idea. You need to create it manually.
idea2020.1. Create a new xml file

There are no fixed requirements for the name and location of the mapping configuration file, but it is commonly named in the format of "entity class name. hbm.xml" (HBM: Hibernate mapping) and created in the package where the entity class is located
Because the configuration file is in xml format, xml constraints need to be introduced into the file. There are two kinds of constraints, dtd and schema
What needs to be introduced here is the dtd constraint. Where can I find the dtd constraint? [dtd constraints to be introduced have been placed below]
The first step is to decompress the downloaded compressed package

E:\hibernate\hibernate-release-5.2.18.Final\hibernate-release-5.2.18.Final\project\hibernate-core\src\main\resources\org\hibernate


Open this document with a WordPad. It is recommended not to use Notepad

The dtd constraint is introduced by copying the part in the red box to the newly created xml file
[contents in red box attached]

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

Next, configure the mapping file
This is my entire mapping file, with detailed comments attached

<?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>
    <!-- 1 Configuration class and table correspondence
		class label
		name Attribute: full path of entity class(Package name+Class name)[To prevent writing errors, select the class name of the entity class,
		Right click, Copy Reference,That is, the full path of this class has been copied]
		table Attribute: the name of the database table. Give yourself a name
	-->
    <class name="com.hiber.bean.Client" table="t_Client">
    
        <!-- Next, configure the correspondence between the attributes in the class and the fields in the table-->
        
        <!-- 2 Configure entity classes id And table id corresponding
			hibernate The entity class is required to have a unique value of the attribute
			hibernate The table is required to have fields as unique values
		-->
        <!-- id label
            name Attribute: in entity class id Attribute name
            column Attribute: generated table field name
         -->
        <id name="cid" column="cid">
            <!-- Set database table id Growth strategy
				native:Generate table id The value is automatically increased by the primary key
			-->
            <generator class="native"></generator>
        </id>
        <!-- Configure other attributes corresponding to table fields
			name Attribute: entity class attribute name
			column Attribute: generate table field name
		-->
        <property name="cName" column="cName"></property>
        <property name="cTelNum" column="cTelNum"></property>
        <property name="cAddress" column="cAddress"></property>
    </class>
</hibernate-mapping>

Create the core configuration file of hibernate

The core configuration file format is xml, but the name and location of the core configuration file are fixed

  • Location: must be under src
  • Name: must be hibernate cfg. XML (cfg: configuration configuration)

The dtd constraint is introduced in the same place as the dtd file in the previous step


Attached contents:

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

During hibernate operation, only the core configuration file will be loaded, and other configuration files will not be loaded, that is, the mapping configuration file in the previous step will not be loaded! Therefore, the mapping configuration file needs to be introduced into the core configuration file
[you need to create the database manually!]
This is my hibernate cfg. XML files cannot be used directly. Some places need to be modified and have detailed comments

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Configure database information -->
        <!--
            Where can I find the configuration of the following database information?
            E:\hibernate\hibernate-release-5.2.18.Final\hibernate-release-5.2.18.Final
            \project\etc
            find hibernate.properties This file (the file is in the form of key value pairs)
            The following four are
            Database driven (be sure to introduce database driven jar Package)
            url,The following is an ellipsis,
                The whole thing is jdbc:mysql://localhost:3306/hibernate_test (this is the database name)
            Database user name
            Database password
        -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate_test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>

        <!-- to configure hibernate information -->
        <!-- Output bottom layer sql sentence -->
        <property name="hibernate.show_sql">true</property>
        <!-- Output bottom layer sql Statement format -->
        <property name="hibernate.format_sql">true</property>
        <!-- hibernate Help create the table after configuring the next sentence
            update: If there is a table, update it. If there is no table, create it
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- Configuration database dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- Put the mapping file into the core configuration file -->
        <mapping resource="com/hiber/bean/client.hbm.xml"></mapping>

    </session-factory>
</hibernate-configuration>

[Note: for the dialect of the configuration database, it needs to be MySQL 5dialect. You can try the difference between MySQL dialect and MySQL 5dialect. The console will output the sql statement for creating a table. You can compare the difference between the two. As a result, MySQL dialect cannot create a data table. I still hope you can try it yourself]
[for importing mapping configuration files, you can press and hold ctrl and click to jump to the correct configuration]

At this point, all configurations are completed!

next,

test

Write a test class

package com.hiber.bean;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;



public class HibernateTest {
    @Test
    public void testAdd(){
        //The first step is to load the hibernate core configuration file
        // Go to src and find the name hibernate cfg. xml
        //Encapsulate objects in hibernate
        Configuration cfg = new Configuration();
        cfg.configure();
        //Step 2: create a SessionFactory object
        //Read the contents of hibernate core configuration file and create sessionFactory
        //In the process, tables are created in the configuration database according to the mapping relationship
        SessionFactory sessionFactory = cfg.buildSessionFactory();
        //Step 3: create a session object using SessionFactory
        // Similar to connection
        Session session = sessionFactory.openSession();
        //Step 4: start the transaction
        Transaction tx = session.beginTransaction();
        //Step 5 write specific logical crud operations
        //Add function
        Client client = new Client();
        client.setcName("petty thief");
        client.setcTelNum("6666666");
        client.setcAddress("Beijing");
        //Call the method of session to add
        session.save(client);
        //Step 6 commit transaction
        tx.commit();

        //Step 7 close resources
        session.close();
        sessionFactory.close();

    }
}

Final result:
The console outputs sql statements for creating tables and adding data

The red box is the database dialect mentioned above, where the two different configurations are different.
At the same time, tables in the database have been created and data has been added

[I wonder if anyone, like me, has encountered the situation that the Chinese data added to the data table is garbled]
My solution:
Add at the url in the hibernate core configuration file:? characterEncoding=utf8

If it is not successful, set the properties of the database, which should be no problem!

[in previous website projects, we often encountered the problem of Chinese garbled code. Generally, a filter can be written for the Chinese data input from the web page to the back-end code. If you operate the database, you'd better refer to the above, which is only a personal summary, which may be biased]

At this point, the test is successfully completed! (this is just a test. Don't write code according to the test method when writing code, and then update the practical CRUD writing method.)

Keywords: Hibernate

Added by Brad7928 on Sat, 22 Jan 2022 11:15:25 +0200