cool hit counter SSH framework journey - hibernate (1)_Intefrankly

SSH framework journey - hibernate (1)


hibernate

1.What is a frame


What is a frame? Personally, I feel that in software design, frameworks can be seen as architectural components. If we consider the whole program as a person, then the framework can be seen as the skeleton of a person, what we have to do is to develop on the basis of this framework, complete the whole program, so that the skeleton of the "person" alive. Whereas some code libraries can be seen as components that encapsulate certain functionality, frameworks are made up of many libraries.

2.Introduction to the SSH framework


SSH be spring struts hibernate abbreviation for。 You can tell by the initials.,SSH is an integrated framework, It is now the more popular Web Open source framework for applications。 The personal line of study is hibernate -> struts -> spring。hibernate is the framework for manipulating the database, belong to Web developed DAO Database operation layer, The underlying layer is a combination of jdbc realized, So as long as there isjdbc basic, Both can start with hibernate learn,hibernate It can also be used in general java of the project's development。

3.Getting to know hibernate


hibernate uses the design idea of orm, which stands for object relationship mapping. That is, the entity class and the database table are one-to-one mapping (correspondence). Specifically, the attributes in the entity class and the fields in the data table correspond one-to-one. What are the benefits of this? This will greatly simplify our operation of the database, the way we manipulate the database, from the original to write a lot of sql statements, to manipulate the database through the database table corresponding to the entity object to manipulate the database.


Here we go through a java project to learn the basics of using hibernate.


The project's directory structure

4.Build the hibernate framework environment


4.1 Preparing the hibernate package

The heinate framework is composed of a number of jar packages, we first have to go to the official website to download the zip archive of hibernate. What is important to note here is the version of hibernate, the version of jdk required for different versions of hibernate is also different, in 2017, the version of hibernate is 5.2. The required jdk support is jdk1.8. hibernate 5.2 is not available for jdk versions lower than jdk1.8. Personally, I've tested hibernate 5.0, which requires jdk1.7+ support. I don't know why, Oracle's official website, now can not directly download the version of jdk1.7, you need to log in, may be Oracle's official website wants to promote developers to use the latest version of jdk to develop it, after all, jdk1.8, that is, java8, which still provides a lot of new features, but also certainly in the previous version of the optimization done. My personal opinion is that the current development is definitely using the latest jdk version for development, and the older versions of jdk are for testing purposes.

4.2 Import the required files for hibernate.

After downloading the zip package from the hibernate website, find the required folder under the lib folder, which contains all the files needed for the hibernate framework, but since the underlying hibernate is still jdbc, we also need the corresponding database driver files. Personally, I recommend storing these jar packages under a separate custom file for ease of use as well.

4.3 Configuration path

Create a new lib folder under the java project to hold our hibernate jar packages and database connection jar packages, and add all of these packages to the configuration path.

hibernate configuration

5.Using the hibernate framework


5.1 Creating entity classes

Modify with private access constraints, use get, set methods to set the value of the property, and you can omit the default constructor method.

package cc.wenshixin.entity;

public class Student {
     private int id;// Serial number
     private String name;// Name
     private String sex;// gender
     private String grade;// class
    
    public Student(String name, String sex, String grade) {
        this.name = name;
        this.sex = sex;
        this.grade = grade;
    }

     // The get and set methods are omitted here
}

5.2 Create entity class mapping file

It is recommended that the mapping file and the entity class file be under the same package and that the mapping file be named: entity-class-name.hbm.xml. dtd is an xml file constraint, the following writeup requires an online state for the xml code hint, for offline dtd configuration, you can search online. A so-called document constraint is one that specifies the format in which the contents of a document are written, specifically the wrapping of tags, the attributes of tags, etc. The mapping file can be generated using the jboss-tool plugin, which can be used by yourself depending on the IDE tool you use.

Here's a little bit about the configuration of the mapping relationship file, as shown in the code below. 1.First. hibernate-mapping tag that wraps the entire mapping relationship. 2.And then there's class Tags, inside name attribute whose value is the full path to the entity class.table is the name of the automatically created data table. 3.id label Configuring primary keys for data tables,name attribute is the name of the attribute that is used as a unique value in the entity class.column attribute as the field name of the generated data table.id Inside the labelgenerator is used to set the policy for primary key growth.native value is automatically growing, theassigned for custom growth. 4.property tag sets the general attribute value of thename property or an entity class property.column is a data table field, this is the same as the previousid label It's the same.。

<?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>
    <class name="cc.wenshixin.entity.Student" table="STUDENT">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <property name="name" column="name"></property>
        <property name="sex" column="sex"></property>
        <property name="grade" column="grade"></property>
    </class>
</hibernate-mapping>

5.3 Creating the hibernate core configuration file

The name is hibernate.cfg.xml, which must be placed under the src directory, and like the entity class mapping file above, the core configuration file is bound by a dtd file.

Here's a little bit about the configuration of the hibernate core files, as shown in the code below. 1.First. hibernate-configuration The tag wraps the entire configuration information. 2.Next. session-factory The tag wraps the entire configuration content. 3.The configured tag is propertyname is the name of the configuration item, and inside the label is the content of the configuration. 4.The first step in the configuration is to configure the database related information, the database driver class, the url parameter for the database connection, the database username, and the user's password. 5.hibernate's feature selection.show_sql is to turn on the ability to display sql statements in hibernate to make it easier for us to do debugging in development.format_sql is the formatting of the displayed sql statements to facilitate our reading of the sql statements.hbm2ddl.auto is about table update operations. update means to create a table if it does not exist, and to update its contents if it does. and create means to create if the table does not exist, but if it does, to overwrite the original table and create a new one, so that the contents of the original table are gone.dialect is the configuration of the database dialect, in different types of data, some sql statements are written differently, for example, the sql statement to be used for paging operations, MySQL database is used limit keyword, whereas the Oracle database is implemented through therownum keyword to achieve this, SQL server databases are implemented through the top keyword to implement, in order to avoid differences in sql statements due to differences in databases, we would be better off adding the dialect feature. 6.Since only the core configuration file will be loaded when hibernate is loaded, add the entity class mapping file to the hibernate core configuration file so that when the core configuration file is loaded, the mapping file will also be loaded, and note that the path to the mapping file should be written in mapping taggedresource Properties in.

<?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>
      <!--  Configuring Database Information -->
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8</property>
      <property name="connection.username">root</property>
      <property name="connection.password">123456</property>

      <!-- hibernate Function Selection -->
      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
      
      <!--  Loading the mapping file -->
      <mapping resource="cc/wenshixin/entity/Student.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

5.4 Creating hibernate test files

After the previous steps, the use of hibernate has been completed, the following is to test through the test file, after the implementation to the database to see if there are corresponding data tables and records.

package cc.wenshixin.hibernateTest;

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

import cc.wenshixin.entity.Student;

public class HibernateTest {
    
    public static void main(String[] args) {
         // 1. Load the hibernate core configuration file
        Configuration cfg = new Configuration().configure();
        
//2. Create a SessionFactory factory, read the core hibernate configuration file in the process, and create the data table based on the mapping relationship
        SessionFactory sessionFactory = cfg.buildSessionFactory();
        
         //3. Use sessionFactory to produce session objects, where the session is similar to a Connection object that connects to the database
        Session session = sessionFactory.openSession();
        
         //4. Opening the transaction
        Transaction transaction = session.beginTransaction();
        
         //5. Perform specific curd operations
        Student s = new Student(" Simon"," male"," computer science2 class");
        session.save(s);

         //6. Submission of transactions
        transaction.commit();
        
         //7. Close related resources
        session.close();
        sessionFactory.close();
    }
}

6.hibernate framework configuration details


6.1 hibernate mapping configuration file

1.The location and name of the mapping configuration file is modifiable, but it is customary to write the name of the mapping configuration file as classname.hbm.xml and put it under the same package as the entity class file

  1. In the mapping profile, the label name attribute whose value is relevant for writing entity classes.class Tagged in. name attribute value is the full path to the entity class, theid Labels and property tagged name The attribute value is the name of the entity class attribute.
  2. id Labels and property label column attribute can be omitted, and the field names of the table are the same as the default if not written name The value of the attribute is the same.
  3. property Also in the tags are type attribute, set the type of the field that generates the word of the table, if you don't write it, hibernate automatically sets the corresponding type. in addition length attribute, which sets the length of the field type, is written in practical development to reduce database redundancy and improve the efficiency of data table queries.

6.2 hibernate core configuration file

1.The three sections in the core configuration file are required, the database configuration information section is required, followed by the section on those features that choose to use hibernate, and finally the loading of the mapping file, which is also required.

2.The file name and location of the core configuration file are fixed, name: hibernate.cfg.xml, location is directly under the src source file directory.

7.The core API of hibernate


7.1 Configuration

Configuration cfg = new Configuration().configure(); Find hibernate... in the src directory. The cfg.xml configuration file, which puts the configuration file into the created configuration object, can simply be interpreted as loading the core configuration file items.

7.2 SessionFactory

SessionFactory sessionFactory = cfg.buildSessionFactory(); Use configuration object to create sessionFactory object, in the process of creating this object, to load the core configuration file mapping file, according to the mapping relationship to create the data table, there may be more than one data table creation, so create a sessionFactory object is quite resource-intensive, a project is recommended to create only one sessionFactory object, usually we are to write this step code to the static code block, so that the code in the static code block will be executed when the class is loaded, and only executed once.

7.3 Session

Session session = sessionFactory.openSession(); The session object is similar to our connection object in jdbc. The session contains various methods for operating on the data table, thus enabling curd operations on the data table. - 1. save method, insert a record - 2. update method, update a record - 3. delete method, delete a record - 4. get method based on id query It should be noted that session is not thread-safe, i.e., session objects cannot be shared by multiple threads and can only be used by a single thread.

7.4 Transaction

Transaction transaction = session.beginTransaction(); Open the database transaction, session object after processing database operations, here you need to manually commit the transaction, the transaction has a commit operation transaction.commit(); And rollback operations transaction.rollback(); , related concepts about transactions, four properties of transactions: atomicity, consistency, isolation, and persistence.


Recommended>>
1、Artificial intelligence faceswapping spreads to adult movies please dont say technology is not guilty
2、Give up the for loop and teach you to use this algorithm
3、What are the current classical target tracking algorithms in computer vision
4、Session technology simple use of cookies
5、Modalities of the Fourth National Economic Census

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号