For more information, see MyBatis: JDBC and MyBatis.

Source: Internet
Author: User

For more information, see MyBatis: JDBC and MyBatis.
JDBC concepts

Java programs connect to the database through JDBC and program the database through SQL. JDBC is a column specification proposed by SUN and only defines the interface specification, the specific implementation is implemented by various database vendors. It is a typical bridge mode.

The bridge mode is a structural design mode. Its main feature is to separate abstract and behavior implementations, define interfaces separately, and maintain the independence of each part and expand their functions.

JDBC Specification

The so-called specification means that you have defined a standard interface and made the following Abstract: Use Connection to represent the Connection to the database, use Statement to execute the SQL Statement, and use ResultSet to represent the results returned by the SQL Statement, it facilitates data. You can create Statement from the Connection, and execute the Statement to obtain the ResultSet.

The Connection, Statement, and ResultSet mentioned above should all be interfaces. The specific implementation is provided by various database providers. With the specification, you can access multiple types of databases through a unified interface and switch the database at will.

Database-driven

As mentioned above, the implementation of interfaces is provided by various vendors, so the class names of implementation classes will be different. When a Connection object is created, the code will write down an implementation class. When the database is switched, it is not good to modify the code. To solve this problem, the Driver concept is abstracted.

Connection con=MySqlConnectionImpl("127.0.0.1",3306,"mi_user",userName,pwd);

Each database must implement the Driver interface. The Driver can obtain the Connection of the database and dynamically create the Connection through the reflection mechanism.

Class.forName("com.mysql.jdbc.Drier");

The same program may access different databases and manage the Driver through DriverManager. during initialization, the Driver must be registered to DriverManager.

DriverManager provides a getConnection method for establishing a database Connection:

Connection con=DriverManager.getConnection("127.0.0.1",3306,"mi_user",userName,pwd);

If there are multiple database drivers, how does DriverManager differentiate them? You need to specify them in the database connection url. For example, mysql needs to add jdbc: mysql Prefix:

String url= "jdbc:mysql://127.0.0.1:3306/mi_user";Connection con=DriverManager.getConnection(url,userName,pwd)
Data Source

The data source contains two parts: the connection pool and the connection pool management. During system initialization, the database connection is stored as an object in the memory. When you need to access the database, a created idle connection object is retrieved from the connection pool.

Use the data source to obtain its DataSource object and dynamically obtain database connections through this object. In addition, the DataSource object can be registered to the Name Service (JNDI), and The DataSource object can be obtained through the name service without the need for a hard-coded driver.

DriverManager is provided by JDBC1 and DataSource is a new feature of JDBC2, providing a better way to connect to the data source.

Comparison between Hibernate and MyBatis

Through the above introduction, the traditional JDBC programming brings us the function of connecting to the database, but the workload is relatively large. First, connect and then process the underlying JDBC transactions and data types, it also captures possible exceptions and closes resources correctly.

In actual work, JDBC is rarely used for programming, and An ORM model is proposed to solve the ing between database data and POJO objects.

Both Hibernate and Mybatis are ORM models. Hibernate provides a full-Table ing model that encapsulates JDBC to a high degree. However, Hibernate also has many disadvantages, as listed below:

  • Inconvenience caused by full table ing, such as sending all fields during update;

  • Different SQL statements cannot be assembled according to different conditions;

  • The support for multi-table join and complex SQL queries is poor. You need to write the SQL statement by yourself. After the result is returned, you need to assemble the data into POJO by yourself;

  • Stored procedures cannot be effectively supported;

  • Although HQL is available, its performance is poor. Large Internet systems often need to optimize SQL, but Hibernate cannot.

In a large Internet environment, flexibility, SQL optimization, and less data transmission are the most basic optimization methods. Hibernate cannot meet the requirements, and MyBatis provides you with a flexible and convenient way, is a semi-automated ing framework.

MyBatis needs to be manually matched to provide POJO, SQL, and ing relationships, while Hibernate for full table ing only needs to provide POJO and ing relationships.

MyBatis can be configured with dynamic SQL to solve the problem of time-based changes of Hibernate table names and different conditions. SQL can be optimized, and SQL ing rules can be determined through configuration. stored procedures are also supported. It is more convenient to query complex and performance-optimized SQL statements.

Core Components

The Core Components mainly include the following:

  • SqlSessionFactoryBuilder: SqlSessionFactory is generated based on the configuration information or code;

  • SqlSessionFactory: Use a factory to generate SqlSession;

  • SqlSession: an interface that can send SQL statements for execution and return results, or obtain Mapper;

  • SQL Mapper: a new component of MyBatis, which consists of a Java interface and an XML file. corresponding SQL and ing rules must be provided. It sends SQL statements for execution and returns results.

Construct SqlSessionFactory

Each MyBatis application is centered on the instance of SqlSessionFactory, and its task is to create SqlSession. SqlSesion is similar to a JDBC Connection object.

Two methods are provided to create SqlSessionFactory: XML configuration and code. XML configuration is recommended.

The definition mybatis-config.xml file is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configuration PUBLIC "-// mybatis.org//DTD Config 3.0 // EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource = "application. properties"> </properties> <! -- Define an alias --> <typeAliases> <typeAlias alias = "role" type = "com. learn. chapter2.po. Role"/> </typeAliases> <! -- Define database information. By default, the development database is used to build the environment --> <environments default = "development"> <environment id = "development"> <! -- Adopt jdbc Transaction Management --> <transactionManager type = "JDBC"/> <dataSource type = "POOLED"> <property name = "driver" value = "$ {driver }"/> <property name = "url" value = "$ {url}"/> <property name = "username" value = "$ {username}"/> <property name =" password "value =" $ {password} "/> </dataSource> </environment> </environments> <! -- Define --> <mappers> <mapper resource = "com \ learn \ chapter2 \ mapper \ roleMapper. xml"/> </mappers> </configuration>

Create SqlSessionFactory

String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
Create SqlSession

SqlSession is an interface class that plays the role of the facade. What actually works is the Executor interface. Make sure that you close it properly after use.

SqlSession sqlSession=null;try{    sqlSession=sqlSessionFactory.openSession();    //some code    sqlSession.commit();} catch(Exception ex){    sqlSession.roolback();} finally{    if(sqlSession!=null){        sqlSession.close();    }}
Er

Mappers are composed of Java interfaces and XML files (or annotations). Their functions are as follows:

  • Define parameter types

  • Description Cache

  • Description SQL statement

  • Define the ing between query results and POJO

First, define the Java interface:

public interface RoleMapper{    public Role getRole(Long id);}

Then, define the XML ing xml file, RoleMapper. XML

<? xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  <mapper namespace ="com.learn.chapter2.mapper.RoleMapper">    <select id="getRole" paramterType="long" resultType="role" >        select id,role_name as roleName , note from t_role where id=#{id}    </select> </mapper>

The Role Definition of the POJO object is relatively simple and will not be listed. # {Id} is the parameter of this SQL statement. If the alias of the SQL column is the same as the attribute name of POJO, the query result of this statement is automatically mapped to the Role attribute, this is automatic ing.

Execute Query

RoleMapper roleMapper=sqlSession.getMapper(RoleMapper.class);Role role=roleMapper.getRole(1L);String roleName=role.getRoleName();
Component lifecycle

SqlSessionFactory in the whole life cycle of the MyBatis application, each database corresponds to only one SqlSessionFactory. You can implement a tool class to obtain this object in singleton mode.

SqlSession is a thread-insecure object in the process of requesting the database to process transactions. Be careful when multithreading is involved. It exists in the request and operation of an application and can execute multiple SQL statements to ensure transaction consistency.

Mapper sends an SQL statement, returns the expected result, or executes an SQL statement to modify the database data. Therefore, it should be executed in a SqlSession transaction method, just like an SQL statement in JDBC, its maximum range is the same as that of SqlSession.

Overall structure of books

This book consists of three parts: basic application, principle, plug-in development, and practical application of MyBatis.

Basic Applications

This section describes how to use MyBatis efficiently:

  • MyBatis features

  • Core Components and their lifecycles

  • MyBatis Configuration

  • Er

  • Dynamic SQL

MyBatis Principle

Deep understanding of the internal running principle of MyBatis and the development methods and skills of the plug-in:

  • This article introduces the parsing and running principle of MyBatis, describes the SqlSession construction method, and how the four objects work.

  • Introduction to MyBatis plug-ins

Practical Application

This section describes some practical scenarios of MyBatis:

  • This section describes how to integrate the MyBatis application in the Spring Project.

  • This section describes the practical scenarios of MyBatis. It selects some typical scenarios and resolves some errors and performance losses that developers need to avoid in each scenario.

Next, we will introduce the configuration of MyBatis, better configure MyBatis for different business scenarios, and provide us with extensions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.