Big data learning_JdbcTemplate and Mybatis comparison

1.JDBC

1.1JDBC concept

JDBC (Java Data Base Connectivity) is a standard specification for Java to access databases. It is a Java API used to execute SQL statements, which can provide unified access to a variety of relational databases. It consists of a set of classes and interfaces written in Java language. . It is the standard specification for Java to access the database.

1.2 JDBC principle

JDBC is an interface, and the driver (JDBC implementation class) is the implementation of the interface. Without a driver, the database connection cannot be completed, so that the database cannot be operated. Each database manufacturer needs to provide its own driver to connect to its own company's database, that is Said driver is generally provided by the database generator.

1.3 Original JDBC operation

// 1.注册驱动
// JDBC规范定义驱动接口: java.sql.Driver
// MySql驱动包提供了实现类: com.mysql.jdbc.Driver
Class.forName("com.mysql.jdbc.Driver");

// 2.获取连接
String url = "jdbc:mysql://localhost:3306/db4?characterEncoding=UTF-8";
String username = "root";
String password = "123456";
Connection getConnection(url, username, password)

JDBC stipulates that the url format consists of three parts, each part is separated by a colon.
The first part is the protocol jdbc, which is fixed; the
second part is the sub-protocol, which is the database name, to connect to the mysql database; the
third part is stipulated by the database manufacturer, we need to understand the requirements of each database manufacturer, the third part of mysql The part consists of the IP address (localhost) of the database server, port number (3306), and the name of the database to be used.
url detailed

// 3.获取statemen对象
Statement statement = con.createStatement();

// 4.编写sql语句
String sql = ;

// 5.执行增删改操作,使用executeUpdate
// 返回值是受影响的行数,如果执行DDL(create 、drop 、alter、truncate table等)时返回值是0
int i = statement.executeUpdate(sql);

// 6.执行查询操作,使用executeQuery
// 返回值是一个ResultSet结果对象,接着可通过遍历得到查询结果
ResultSet resultSet = statement.executeQuery(sql);

//7.关闭流
statement.close();
con.close();

1.4 Summary of steps

  1. Get driver (can be omitted)
  2. Get connection
  3. Get the Statement object
  4. Processing the result set (only processed at query time)
  5. Release resources

1.5 Disadvantages of native JDBC

  • Frequent database connection creation and release cause waste of system resources and affect system performance
  • The sql statement is hard-coded in the code, which makes the code difficult to maintain. The actual application of sql may change greatly, and the change of sql requires changing the java code.
  • When querying, you need to manually encapsulate the data in the result set into an entity.

2.JdbcTemplate

2.1 JdbcTemplate concept

JdbcTemplate is a template object provided in the spring framework, which is a simple encapsulation of the original cumbersome JdbcAPI object.
Core object: JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSource dataSource);

2.2JdbcTemplate operating database

// 1.创建核心对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());

// 2.编写sql
String sql = ;

// 3.执行语句
// 增、删、改语句使用update方法
int i =  jdbcTemplate.update(sql,arg..); 
// 单个查询语句语句使用queryForObject方法
Object obj = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Object.class));
// 多个查询语句语句使用query方法
List<Object> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Object.class));

advantage

  • Using JdbcTemplate can save a lot of redundant code (create connection, close connection, handle exception), because the JdbcTemplate class will automatically handle it. Just focus on business logic.
  • Query results are automatically encapsulated as class objects
  • Simple and efficient

Disadvantage

  • The same sql statement has a hard-coded problem in the code.

3.Mybatis

3.1 Mybatis concept

MyBatis is an excellent ORM-based semi-automatic lightweight persistence layer framework. It encapsulates the process of operating the database of jdbc so that developers only need to pay attention to the SQL itself, instead of spending energy on processing such as registering drivers, creating connections, Jdbc complicated process codes such as creating statement, manually setting parameters, and result set retrieval.

3.2 Mybatis principle

ORM thinking

  • O (Object Model): Entity object, which is the entity javaBean that we build in the program according to the database table structure
  • R (data structure of relational database): Relational (established database table) in the field of relational database
  • M (mapping): The mapping from R (database) to O (object model) can be mapped through an XML file

Implementation

  • Let entity classes and database tables have a one-to-one correspondence
    • Let the entity class correspond to the database table first
    • Let the entity class attributes correspond to the fields in the table
  • No need to directly manipulate the database table, directly manipulate the entity class object corresponding to the table

Mybatis uses ORM to solve the problem of entity and database mapping, encapsulates jdbc, shields the details of the underlying access of jdbc api, so that we can complete the persistence operation of the database without dealing with jdbc api.

3.3 Mybatis operation database

Mybatis operating database is divided into traditional development method and agent development method. The difference is that in the traditional development method, you need to write the implementation class of the interface. In the implementation class, you need to obtain the session object and call the method to operate the database. In this way, there is a mybatis template in the implementation class. The code is repeated; and when the implementation class calls the method, the sql statement in the xml will be hard-coded into the java code.
The agency development method solves this problem and is now the mainstream of enterprises.
The following steps to operate the database take the agent development method as an example:

1.mybatis configuration

  • Write the MyBatis core file
    SqlMapConfig.xml, this file is used as the global configuration file of mybatis, which configures the operating environment of mybatis and other information (data sources, things, mapper mapping files).
  • Write the Mapper mapping file. The
    mapper.xml file is the sql mapping file. The sql statement for operating the database is configured in the file. This file needs to be loaded in SqlMapConfig.xml.
    • The namespace in the Mapper.xml mapping file is the same as the fully qualified name of the mapper interface
    • The Mapper interface method name is the same as the id of each statement defined in the Mapper.xml mapping file
    • The input parameter type of the Mapper interface method is the same as the parameterType of each SQL defined in the mapper.xml mapping file
    • The output parameter type of the Mapper interface method is the same as the resultType of each SQL defined in the mapper.xml mapping file
    • specification

2. Write the interface

3. Write the test class

// 1.加载核心配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");

// 2.获取SqlSessionFactory工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

// 3.由会话工厂创建SqlSession会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();

// 执行sql
List<User> list = sqlSession.selectList("UserMapper.findAll");

// 释放资源
sqlSession.close();

Summary: Through the proxy development method, you only need to write the Mapper interface, and the Mybatis framework will dynamically generate implementation class objects for the interface.

3.4 The internal execution principle of Mybatis based on the interface proxy method

In the proxy development model, we only established an interface in the persistence layer. By tracking the source code, we found that the mapper used is actually a proxy object, which is generated by the MapperProxy proxy.
Insert picture description here
Tracing the invoke method of MapperProxy will find that it finally calls mapperMethod.execute(sqlSession, args).
Insert picture description here
When you enter the execute method, you will find that sqlSession ultimately works.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41612830/article/details/112307690