Novice web development simple summary (13)-related optimization of database connection (use of Hibernate)

table of Contents

Preface

One Hibernate

1. What is Hibernate

2. Hibernate several important class objects

(1) Configuration object Configuration

(2)SessionFactory

(3)Session

(4)Transaction

(5)Query和Criteria

Two examples

三 Hibernate Template

Four summary


Preface

In the simple summary of novice web development (12)-database connection optimization (transaction management) , I mainly learned the basic knowledge of transaction management provided by Spring, and understood what is a transaction. Spring has two ways of transaction management. How to use some excellent frameworks like Hibernate/Mybatis in usual projects? This time I summarize Hibernate

One Hibernate

1. What is Hibernate

Hibernate object-relational mapping framework, namely ORM (Object-Relational Mapping) framework.

A simple summary of web development for novices in Xiaobai (12)-Related optimization of database connection (transaction management) in the verification declarative transaction management instance ( https://github.com/wenjing-bonnie/sql-web.git in ), one of BookManagerXmlTransactionService uses jdbcTemplate.queryForObject() to query a custom entity class object, the code is as follows:

    private Book getBookSQL(String table, String id) {
        String sql = String.format("SELECT * FROM %s WHERE id=%s", table, id);
        Book book = jdbcTemplate.queryForObject(sql, new RowMapper<Book>() {
            @Override
            public Book mapRow(ResultSet resultSet, int i) throws SQLException {
                Book item = new Book();
                item.id = resultSet.getInt(1);
                item.name = resultSet.getString(2);
                item.price = resultSet.getFloat(3);
                item.online = resultSet.getDate(4).toString();
                return item;
            }
        });
        //在查询的过程中插入同样id的数据,如果启动了事务,则不会插入成功
        return book;
    }

In this process, we use RowMapper to convert the ResultSet into a custom Book object. This process of mapping a relational database to a Java object is an ORM. ORM can not only convert line records into JavaBeans, but also convert JavaBeans into line records.

JdbcTemplate and RowMapper are the most primitive ORM, while Hibernate is a mature automated ORM. Hibernate can automatically generate SQL statements and execute them automatically. Then you can use Hibernate instead of JdbcTemplate to add, delete, modify, and query the database, and become a more commonly used bridge between Java Bean and database server.

Hibernate supports almost all relational databases (RDBMS), like common MySQL, PostgreSQL, Oracle, Microsoft Server Database, etc.

2. Hibernate several important class objects

Hibernate supports JDBC transactions, JTA transactions, and JNDI (Java Naming and Directory Interface). JTA and JNDI allow Hibernate to inherit from the J2EE application server.

Note: JNDI: Java Naming and Directory Interface (Java Naming and Directory Interface), can be simply understood as renaming the resource, and then finding the resource based on the naming.

(1) Configuration object Configuration

Mainly used to configure and start Hibernate. It is usually only allowed to be created when the application is initialized. Configuration provides two basic components: database connection and class mapping configuration.

  • Database connection: Because Hibernate replaces the previous JdbcTemplate, the database driver class, url, user name and other parameters need to be configured here. The configuration files are hibernate.properties and hibernate.cfg.xml;
  • Class mapping configuration: create the relationship between the object and the database table.

In this way, Hibernate specifies the object-relational mapping file through an instance of Configuration, and creates an instance of SessionFactory.

(2)SessionFactory

Corresponding to the data source, there is Configuration generated, which encapsulates the JDBC DataSource instance. Do not generate multiple instances at will: For single-database applications, generally only one SessionFactory needs to be generated. If there are multiple databases, you also need to create a SessionFactory for each database.

The SessionFactory holds a database connection pool because of the encapsulated DataSource. Every time a Session is created from the SessionFactory, it actually takes out a new Connection from the connection pool.

Thread safety, the same instance can be shared by multiple threads of the application. A large number of predefined SQL statements and mapping metadata are stored in the SessionFactory.

(3)Session

A session for the physical connection with the database. A JDBC Connection instance is encapsulated inside. Obtained from SessionFactory. Each instantiation needs to interact with the database.

The Session object should not remain open for a long time, it is not thread-safe, and needs to be created and destroyed on demand.

There is a cache in the Session, called the first-level cache in Hibernate, which stores the persistent objects loaded by the current unit of work. Each Session has its own cache, and the objects in the cache can only be accessed by the current unit of work.

(4)Transaction

Database transaction interface. The bottom layer is handled by the transaction manager and transaction (JDBC or JTA). The transaction boundary can be declared through the consistent Transaction interface, which can be transplanted in different environments or containers.

(5)Query和Criteria

Query is used to query the database for objects and control the process of executing the query. Query encapsulates a HQL to query, while Criteria completely encapsulates query statements based on string form, which is more object-oriented than Query and is good at dynamic queries. This category contains the data last queried in the database.

Two examples

Still add code on the basis of https://github.com/wenjing-bonnie/sql-web.git . It is simply to add a librarian to a new table librarian.

  • 1. To use Hibernate, it is of course necessary to increase the corresponding dependency in pom.xml
     <!--hibernate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.12.Final</version>
        </dependency>
        <!--Spring ORM 包含Spring对DAO特性集进行了扩展-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

The jar file spring-orm contains Spring's extension of the DAO feature set to support iBATIS, JDO, OJB, TopLink, because Hibernate has been packaged independently and is not included in this package now. Most of the classes in this jar file depend on the classes in spring-dao.jar. When using this package, you need to include the spring-dao.jar package at the same time.

  • 2. Create the entity class Librarian of the table

Specifically, the fields and get/set methods corresponding to some tables. For the specific code, please refer to the code in com.wj.hsqldb.model.Librarian.

@Entity
public class Librarian {
  
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private int age;
    private String sex;

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

    @Id
    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getSex() {
        return sex;
    }

    @Override
    public String toString() {
        return "Librarian{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }

}

Note that this class must be added with javax.persistence.Entity annotation, otherwise it will throw org.hibernate.MappingException: Unknown entity: com.wj.hsqldb.model.Librarian exception.

Leftover problem: There must be a way to directly convert the database table into an entity class object, but I don’t know how to do it now, let’s learn about it later

  • 3. Create Spring configuration file application-context-hibernate.xml

Because Hibernate is just an object-relational mapping framework, it just solves the problem of converting the ResultSet into a custom object through RowMapper in jdbcTemplate.queryForObject(), so the transaction management and data source of the read and write database still need to be compared with the previous Xiaobai Novice web development brief summary (12)-Database connection optimization (transaction management) in order to add transaction management, but now the PlatformTransactionManager of things is org.springframework.orm.hibernate5.HibernateTransactionManager that was not specifically introduced last time.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--增加数据库配置的配置文件-->
    <context:property-placeholder location="classpath:config/jdbc.properties"/>
    <context:component-scan base-package="com.wj.hsqldb"/>
    <!--配置数据源-->
    <bean id="hiDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="initialPoolSize" value="3"/>
        <property name="maxPoolSize" value="6"/>
    </bean>
    <!--添加SessionFactory-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="hiDataSource"/>
        <!--<property name="mappingResources"> 指定classpath下具体映射文件名或者利用list同时指定多个 映射文件
         mappingLocations:可以指定任何文件路径,并且可以指定前缀:classpath、file等
         -->
        <!--        <property name="mappingLocations">-->
        <!--            <value>com/wj/hsqldb/model/Librarian.hbm.xml</value>-->
        <!--        </property>-->
        <property name="packagesToScan">
            <list>
                <value>com.wj.hsqldb.model</value>
            </list>
        </property>

        <!--(第一种)也可以通过配置properties的方式来配饰-->
        <!--        <property name="hibernateProperties">-->
        <!--            <props>-->
        <!--                <prop key="dialect"></prop>-->

        <!--            </props>-->
        <!--        </property>-->
        <!--(第二种)也可以通过配置properties的方式来配饰-->
        <property name="configLocation" value="classpath:config/hibernate.cfg.xml"/>
    </bean>
    <!--配置Spring事务-->

    <bean id="hiTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!--    配置事务属性-->
    <tx:advice id="txAdvice" transaction-manager="hiTransactionManager">
        <tx:attributes>
            <tx:method name="get*"/>
            <tx:method name="*Librarian"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入点-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.wj.hsqldb.service.LibrarianManagerService.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans>

 The difference is that:

(1) The property referenced by transaction management has changed: add <property name="sessionFactory"> in HibernateTransactionManager; add <property name="dataSource"> in DataSourceTransactionManager

(2) Additional definition of LocalSessionFactoryBean needs to be added: there are several attributes

        <property name="dataSource">Configure the data source of SessionFactory

       <property name="packagesToScan">Specify the path of the file in .hbm.xml

       <property name="configLocation" >Configure the Hibernate configuration file or directly read the configuration items in the .properties file through <property name="hibernateProperties">

  • 4. Hibernate configuration file hibernate.cfg.xml

There are actually two ways to implement this Hibernate configuration item:

One is through .properties, which is read through <property name="hibernateProperties"> in application-context-hibernate.xml;

Another way is to add the hibernate.cfg.xml file and read it through <property name="configLocation"> in application-context-hibernate.xml

The specific configuration content is as follows:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
<!--        <property name="connection.url">jdbc:hsqldb:file:db/hsqldb/xbook</property>-->
<!--        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>-->
<!--        <property name="connection.username">SA</property>-->
<!--        <property name="connection.password"></property>-->
        <!--转换为合适的数据库语句-->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <!--是否显示sql语句-->
        <property name="hibernate.show_sql">true</property>
        <!--update:只是更新,没有就创建;create:每次都是新创建;create-drop用完就会删除表-->
        <!--我现在理解的是update用完一次要记得隐藏-->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!--下一层级的映射关系,用来配置JavaBean与数据库之间的关系-->
    </session-factory>
</hibernate-configuration>

From the hidden code, you can see that some properties such as url and user name of the database can also be configured, but the configuration in the previous application-context-hibernate.xml cannot be repeated. Mainly explain several attributes inside:

(1) "hibernate.hbm2ddl.auto" : Whether to rely on hibernate to build the table

<property name="hibernate.hbm2ddl.auto">update</property>

The functions of several parameters of hibernate.hbm2ddl.auto are as follows:

  • create: Each time hibernate is loaded, the last generated table will be deleted, and then a new table will be regenerated based on the Java object, which will cause database data loss
  • create-drop: Every time hibernate is loaded, a table is generated based on the Java object, but the table will be automatically deleted as soon as the SessionFactory is closed
  • update: The first time hibernate is loaded, it will automatically create a table structure based on the Java object (provided that the database has been established), if not, it will automatically create a new table. When hibernate is loaded in the future, the table structure is automatically updated according to the Java object, even if the table structure changes, the previous row will not be deleted
  • validate: every time hibernate is loaded, it will be marked with the table in the database, a new table will not be created, but a new value will be inserted

Remaining problem: This property, especially during the use of update, only occurs when the project is run for the first time. If there is no update to the content of the database, you need to change "<property name="hibernate.hbm2ddl.auto"> update</property>" to hide, otherwise an exception "java.sql.SQLSyntaxErrorException" will be thrown

	Caused by: java.sql.SQLSyntaxErrorException: object name already exists: LIBRARIAN in statement [create table Librarian (id bigint not null, age integer not null, name varchar(255), sex varchar(255), primary key (id))]
		at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
		at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)

You can see from the SQL statement that the command executed in update is "create table", not "create table if not exist". I don’t know if there are additional attributes that can solve the situation that the database does not change

       (2) "dialect" : dialect. Corresponding to each specific database, corresponding SQL statements are generated for the specific database.

        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

 List the dialects corresponding to different databases, that is, the configuration value of this attribute:

database dialect
DB2 org.hibernate.dialect.DB2Dialect
HSQLDB org.hibernate.dialect.HSQLDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Informix org.hibernate.dialect.InformixDialect
Ingres org.hibernate.dialect.IngresDialect
Interbase org.hibernate.dialect.InterbaseDialect
Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
MySQL org.hibernate.dialect.MySQLDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 11g org.hibernate.dialect.Oracle10gDialect
Oracle 10g org.hibernate.dialect.Oracle10gDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
Progress org.hibernate.dialect.ProgressDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialec

(3) hibernate.show_sql : whether to display the SQL statement

   <property name="hibernate.show_sql">true</property>
  •  5. Increase the mapping configuration file Librarian.hbm.xml

Generally placed in the package where the entity class is located. This file is mainly to establish the mapping relationship between tables and classes.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.wj.hsqldb.model">

    <class name="com.wj.hsqldb.model.Librarian" table="librarian">
        <id name="id" type="long" column="id">
            <generator class="identity"></generator>
        </id>
        <property name="name" type="string" column="name"/>
        <property name="age" type="java.lang.Integer" column="age"/>
        <property name="sex" type="java.lang.String" column="sex"/>
    </class>

</hibernate-mapping>

Others are relatively easy to understand, mainly look at the attributes of the following primary key generation strategy

 <generator class="increment"></generator>

The generator has the following properties:

  • identity: increasing. Use the primary key generation mechanism provided by the database. For example, the primary key generation mechanism of DB2, SQL Sever MySQL, that is, the primary key needs to be set to auto_increment when building a table using an increasing sequence;
  • sequence: Use the sequence mechanism provided by the database to generate the primary key, such as an Oracle database
  • hilo: There is a primary key generation mechanism implemented by the hi/lo algorithm, and an additional database table is required to store the historical state of primary key generation
  • Native: Hibernate uses one of identity, hilo, and sequence as the primary key based on the underlying database, and the underlying dialect is generated.
  • seqhilo: Similar to hilo, except that the history of the primary key is stored in the Sequence, which is suitable for databases that support Sequence, such as Oracle
  • increment: The primary key is incremented in numerical order. The implementation mechanism is to maintain a variable in the current application instance to save the current maximum value, and then add 1 to this basis each time; however, there are currently multiple instances to access the same database, which may cause duplicate primary keys
  • assigned: generated by an external program without Hibernate participation
  • foreign: Use the field of the foreign table as the primary key
  • uuid.hex: Based on the 128-bit unique value generation algorithm to generate hexadecimal values ​​as the primary key
  • uuid.string: similar to uuid.hex, but the generated primary key is not encoded

During this process, the table appears in the Librarian.hbm.xml created at the beginning and the database fields appear red. You can refer to the table in the Librarian.hbm.xml file in Hibernate and the fields appear red-IDEA configuration DataSource

Remaining problem: There is a way to automatically generate the .hbm.xml file, but you need to look at it later.

  • 6. Create a LibrarianManagerService that operates the database

The SessionFactory is introduced into this class, and the Session is obtained through the SessionFactory to read and write the database.

@Component
public class LibrarianManagerService {
    private String tableName = "librarian";
    @Resource
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * TODO id到底怎么进行自增???
     *
     * @return
     */
    public void insertLibrarian(Librarian librarian) {
        String sql = String.format("SELECT * FROM %s", tableName);
        List<Librarian> librarians = getSession().createSQLQuery(sql).addEntity(Librarian.class).list();
        if (librarians == null || librarians.isEmpty()) {
            librarian.setId(new Long(1));
        } else {
            librarian.setId(new Long(librarians.size() + 1));
        }
        //使用Session
        getSession().save(librarian);
        //使用HibernateTemplate
        //hibernateTemplate.save(librarian);
    }

    /**
     * 获取所有的管理员
     *
     * @return
     */
    public List<Librarian> getLibrarian() {
        String sql = String.format("SELECT * FROM %s", tableName);
        Query query = getSession().createSQLQuery(sql).addEntity(Librarian.class);
        return query.list();
    }
    //取得持久化对象的方法: get() load()
    //持久化对象保存,更新和删除:save(),update(),saveOrUpdate(),delete()

}

Remaining question: How to insert objects for real auto-increment id in the project? 

  • 7. Create the corresponding Servlet and .jsp files to complete the business logic

Add specific business logic, here is just a simple implementation of saving the name, age, and gender information in Librarian to the corresponding table, and then query the data in the database. The specific class corresponds to com.wj.hsqldb.controller. LibrarianController and addlibrarian.jsp, the code is not listed, you can go directly to github to view https://github.com/wenjing-bonnie/sql-web.git The corresponding code tag is example13-1 (because the project is always updated, so Mark this code by tagging)

After running the project through IDEA's tomcat, you can directly enter the corresponding page through http://localhost:8080/librarian/addlibrarian.jsp , click save, the data of the database will be output in the log corresponding to IDEA.

三 HibernateTemplate

Of course, Spring also provides HibernateTemplate to encapsulate the above process, simplifying the process of data access (that is, encapsulating the process of obtaining the session from the SessionFactory and managing the session, etc.), and supports single SQL transaction management.

Note that the HibernateTemplate here generally appears in the DAO layer. The so-called transaction management is only for a single SQL, that is, the single SQL statement may contain multiple database operations, that is, only for the Service layer. The transaction processing of the business logic layer (the combination of calling the DAO layer for business logic) still has to be handed over to Spring's transaction management.

Therefore, compared to the logic of replacing the session of LibrarianManagerService to read and write the database in the second instance, the session logic in LibrarianManagerService is not perfect. There should be some session management: such as setting, opening, and releasing some properties. . Therefore, HibernateTemplate adds more of these logic packages, and database operations can be completed only by calling the HibernateTemplate object.

Therefore, the comparison between Session and HibernateTemplate can refer to the relationship between JdbcTemplate and Conection.

The use process is nothing more than adding HibernateTemplate on the original basis

    <!--增加HibernateTemplate-->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

 For specific usage, please refer to the related code of com.wj.hsqldb.service.LibrarianManagerService. From the code, it can be seen that using HibernateTemplate is more convenient than simply using Session. Like query functions, you can directly obtain the corresponding entity class collection:

  List<Librarian> result = hibernateTemplate.loadAll(Librarian.class);

The code is not listed, you can go directly to github to view https://github.com/wenjing-bonnie/sql-web.git. The corresponding code tag is example13-2 (because the project is always updated, so by tagging Mark this time code) 

Four summary

I encountered some problems in the process of this example, let's briefly summarize.

  • 1. Inserting data through session.save() throws org.hibernate.MappingException: Unknown entity: com.wj.hsqldb.model.Librarian exception.

Phenomenon: When running the project, the error message in the browser is as follows:

Reason: The mapped entity object needs to add javax.persistence.Entity annotation.

Solution: Add the @Entity annotation to the Librarian class. At the same time, you will be prompted to specify an @Id attribute, just follow the error message and complete it step by step.

  • 2. Query data through session.createSQLQuery(). When looping through the collection elements, throw java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.wj.hsqldb.model.Librarian

The original query code is as follows:

    public List<Librarian> getLibrarian() {
        String sql = String.format("SELECT * FROM %s", tableName); 
        Query query = getSession().createSQLQuery(sql);
        return query.list();
    }

Then loop to output the collection elements returned by getLibrarian().

Phenomenon: When running the project, the error message in the browser is as follows:

Reason:  query.list() returns List<Object> type

Solution: Add the corresponding entity class type after session.createSQLQuery(). The modified code is as follows:

 Query query = getSession().createSQLQuery(sql).addEntity(Librarian.class);

Extension: In fact, two query methods are provided in the hibernate Session: one is createSQLQuery() and the other is createQuery(). Both of these methods can return eligible data in the corresponding table in the database, but two There are certain differences:

createSQLQuery(): SQL statement query; the data after the query is stored in an array; it needs to be converted into a collection of entity object types through addEntity()

createQuery(): hql statement query; the data after the query is stored as a List; it can directly return the collection of the corresponding entity object type

The specific usage is as follows:

After querying the data through createSQLQuery(), the collection of entity objects returned is as follows:

    public List<Librarian> getLibrarian() {
        //sql语句
        String sql = String.format("SELECT * FROM %s", tableName);
        //createSQLQuery
        Query query = getSession().createSQLQuery(sql).addEntity(Librarian.class);
        //调用.list()返回集合
        return query.list();
    }

And the collection of entity objects returned after query by createQuery() is as follows:

    public List<Librarian> getLibrarian() {
        //hql语句
       String  hql = String.format("from Librarian %s ", tableName);
        //调用createQuery
        Query<Librarian> other = getSession().createQuery(hql, Librarian.class);
         //调用.list()返回集合
        return other.list();
    }

 Through these two methods, you can see that the final statement executed by Hibernate is also different: one executes the SQL statement directly, and the other executes the hql statement.

= createSQLQuery = 
Hibernate: SELECT * FROM librarian
Librarian{id=1, name='小刘', age=34, sex='女'}
Librarian{id=2, name='小刘', age=23, sex='男'}
Librarian{id=3, name='六', age=78, sex='男'}
 = createQuery = 
Hibernate: select librarian0_.id as id1_0_, librarian0_.age as age2_0_, librarian0_.name as name3_0_, librarian0_.sex as sex4_0_ from Librarian librarian0_
Librarian{id=1, name='小刘', age=34, sex='女'}
Librarian{id=2, name='小刘', age=23, sex='男'}
Librarian{id=3, name='六', age=78, sex='男'}
  • 3. When IDEA is running Tomcat, the console reports "Failed to load class "org.slf4j.impl.StaticLoggerBinder", and the console cannot print the log log of the project that has not started running abnormally.

Phenomenon: When running Tomcat, the console reports "Failed to load class "org.slf4j.impl.StaticLoggerBinder", and when the project is not successfully started, the log log cannot be viewed (add screenshots!!!!!! !)

Reason: Follow the prompts to enter http://www.slf4j.org/codes.html#StaticLoggerBinder%C2%A0 (add screenshots!!!), find that slf4j-nop.jar slf4j-simple.jar is missing, One of slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar, and only one can be added to the project.

Solution : Add one of the corresponding dependencies in pom.xml (replace!!!!!! Replace with slf4j-log4j12.jar)

     <!--Failed to load class "org.slf4j.impl.StaticLoggerBinder"
        还可以让tomcat的输出启动不成功的日志-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.5</version>
            <scope>compile</scope>
        </dependency>
  • 4. The database table name and database field in Librarian.hbm.xml in IDEA are reported in red

For details, please refer to the table and fields in the Librarian.hbm.xml file in Hibernate to show red-IDEA configuration DataSource 

  • 5. Summary of Hibernate's knowledge points

(1) Hibernate is a framework of object mapping relations, similar to Mybatis, etc., and corresponding data sources and transactions need to be added to assist in reading and writing databases;

(2) Hibernate loads the SessionFactory through the configuration file, and configures the relevant properties of the SessionFactory;

(3) The SessionFactory contains DataSource, which requires special transaction management, and the SessionFactory needs to be configured into the transaction management;

(4) Session contains Connection, which is used to generate a connection to read and write the database;

(5) Hibernate maps the direct relationship between the table and the object through .hbm.xml, and puts it in the corresponding package of the object through this file;

(6) Query and Criteria are the results of data query;

(7) HibernateTemplate can further encapsulate the process of reading and writing databases and relational mapping, and add transaction management to a single SQL, but it also needs to rely on Spring for transaction management related to business logic.

  • 6. Legacy issues

(1) There must be a way to directly convert the database table into an entity class object, but now I don’t know how to do it, let’s learn about it later

(2) The method of automatically generating the .hbm.xml file, but you need to look at it later.

 Because of the needs of project progress, I don't know Mybatis for the time being, first look at the optimization of Controller and jsp files related to business logic.

Guess you like

Origin blog.csdn.net/nihaomabmt/article/details/114653265