Several problems of native jdbc and introduction to mybatis

Intercepted from: http://www.cnblogs.com/selene/p/4604605.html

 

The following is the native jdbc connection database code:

public class JdbcTest {
    public static void main(String[] args) {

        // Database linkage
        Connection connection = null;
        // Precompiled Statement, use precompiled Statement to improve database performance
        PreparedStatement preparedStatement = null;
        // result set
        ResultSet resultSet = null;

        try {
            // load database driver
            Class.forName("com.mysql.jdbc.Driver");

            // Get the database link through the driver management class
            connection = DriverManager
                    .getConnection(
                            "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
                            "root", "root");
            // Define sql statement? Represents a placeholder
            String sql = "select * from t_user where username = ?";
            // Get the preprocessing statement
            preparedStatement = connection.prepareStatement(sql);
            // Set parameters, the first parameter is the serial number of the parameter in the sql statement (starting from 1), and the second parameter is the set parameter value
            preparedStatement.setString(1, "王五");
            // Send sql to the database to execute the query, and query the result set
            resultSet = preparedStatement.executeQuery();
            // Traverse the query result set
            while (resultSet.next()) {
                System.out.println(resultSet.getString("id") + "  "
                        + resultSet.getString("username"));
            }
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            // release resources
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                }
            }

        }

    }
}

 Summary of the problem with the code above:

1. The database connection is created when it is used, and is released immediately if it is not used. Frequent opening and closing of the database connection results in a waste of database resources and affects the performance of the database.

Solution: Use a database connection pool to manage database connections.

2. Hard-code the sql statement into the java code. If the sql statement is modified, the java code needs to be recompiled, which is not conducive to system maintenance.

Solution: configure the sql statement in the xml configuration file, even if the sql changes, the java code does not need to be recompiled.

3. Set parameters in preparedStatement, hard-code the position of placeholders and set parameter values ​​in java code, which is not conducive to system maintenance.

Solution: Configure all SQL statements, placeholders and parameters in xml.

4. When traversing the result set data from the resutSet, there is hard coding, which is not conducive to system maintenance.

Solution: Automatically map the result set of the query into a java object.

 

What is MyBatis?

 MyBatis is an open source project of apache , iBatis . In 2010, this project was migrated from apache software foundation to google code and renamed MyBatis. In essence, Mybatis made some improvements to ibatis. 

  MyBatis is an excellent persistence layer framework. It encapsulates the process of operating the database of jdbc, so that developers only need to pay attention to SQL itself, and do not need to spend energy to deal with such as registering drivers, creating connections, creating statements, manually setting parameters, Result set retrieval and other jdbc complex process code.

 

  Mybatis configures the various statements to be executed (statement, preparedStatemnt, CallableStatement) through xml or annotation, and maps the java object and the sql in the statement to generate the final executed sql statement. Finally, the mybatis framework executes the sql and generates the result. Map to java object and return.

 

The architecture diagram is as follows



 

 

mybatis configuration

SqlMapConfig.xml, as the global configuration file of mybatis, this file configures the running environment of mybatis and other information.

The mapper.xml file is the sql mapping file, and the sql statement for operating the database is configured in the file. This file needs to be loaded in SqlMapConfig.xml.

 2. Construct SqlSessionFactory, the session factory, through configuration information such as the mybatis environment

 3. The sqlSession is the session created by the session factory, and the operation of the database needs to be done through the sqlSession.

 4. The bottom layer of mybatis customizes the Executor executor interface to operate the database. The Executor interface has two implementations, one is the basic executor and the other is the cache executor.

 5、Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。

 6、Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数。

 7、Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326152400&siteId=291194637