Introduction to MYBATIS:JDBC and MyBatis in layman's

Source: Internet
Author: User
Tags connection pooling

Recently in the Hugh paternity leave, time is more fragmented, ready to see 2 of books enriched, one is "MyBatis: Technical Principles and practice", one is "RABBITMQ combat: efficient deployment of distributed Message Queuing, in order to deepen memory and understanding, will be organized, expanded and recorded.

The goal of reading is not to remember all the details, but to understand the overall understanding of what a technology can do, including features, basic modules, implementation principles and common usage scenarios.

This article shares the first article of MyBatis book, first recall the related concepts of JDBC, understand the basic way that Java provides access to the database, and then introduce the basic features and core components of the MyBatis, and finally the overall structure of the book, to understand the general contents of the following articles.

JDBC Related concepts

Java programs are connected to the database through the JDBC, through SQL to the database programming, JDBC is by the Sun company Some column specification, only defines the interface specification, concrete implementation by each database vendor to implement, it is a typical bridge mode.

Bridge mode is a kind of structural design pattern, its main characteristic is to separate the abstraction from the behavior realization, define the interface separately, can maintain the independence of each part and deal with their function extension.

JDBC Specification

The so-called specification, is the definition of the standard interface, do the following abstract: With connection representative and database connection, with statement Execute SQL, with ResultSet to represent the results of SQL return, provides the data convenience. From connection can create statement,statement execute query to get resultset.

The above mentioned connection, Statement, resultset should be the interface, the specific implementation by the various database providers. With the specification, through a unified interface, access to a variety of types of databases, you can easily switch databases.

Database-driven

As mentioned above, the implementation of the interface is provided by each vendor, then the implementation class name will not be unified, to create connection object, the code will write to die an implementation class, switch the database, you need to modify the code, this is not very good. In order to solve this problem, the concept of driver drive is abstracted.

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

Each database needs to implement the driver interface, which is created dynamically through the reflection mechanism through the driver to obtain the database connection connection.

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

The same program may access different databases, manage drivers through DriverManager, and driver will need to be registered with DriverManager when initializing.

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, drivermanager how to differentiate between, need to be specified in the database connection URL, such as MySQL need 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 datasource contains connection pooling and connection pooling Management 2 parts, which are customarily referred to as connection pooling. When the system is initialized, the database connection is stored as an object in memory, and an established idle connection object is fetched from the connection pool when the database needs to be accessed.

Use a data source to get its DataSource object, which dynamically gets a database connection through that 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 hard-coded drivers.

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

Compare Hibernate and MyBatis

Through the above introduction, the traditional JDBC programming brings us the function of connecting the database, but its workload is relatively large, first connecting, then processing the JDBC underlying transaction, processing the data type, and catching the possible exceptions and closing the resources properly.

In practical work, JDBC is seldom used to program, and the ORM model is proposed to solve the mapping between database data and Pojo objects.

Hibernate and MyBatis are ORM models, and Hibernate provides a model of full table mapping with a high degree of encapsulation of JDBC. But hibernate also has a number of shortcomings, listed as follows:

    • The inconvenience caused by full table mapping, such as the need to send all fields when updating;
    • Unable to assemble different SQL according to different conditions;
    • For multi-table association and complex SQL query support is poor, you need to write your own SQL, return, you need to assemble the data into Pojo;
    • Cannot effectively support stored procedures;
    • Although there are hql, but poor performance, large-scale Internet systems often need to optimize SQL, and hibernate do not.

Large-scale Internet environment, flexible, SQL optimization, reduce data transmission is the most basic optimization method, Hibernate can not meet the requirements, and MyBatis oh give you a flexible, convenient way, is a semi-automatic mapping framework.

MyBatis requires manual matching to provide Pojo, SQL, and mapping relationships, while hibernate for full table mappings only needs to provide pojo and mapping.

MyBatis can be configured with dynamic SQL, you can resolve hibernate table names according to the time change, the different conditions below are not the same problem. SQL can be optimized, configuration-determined SQL mapping rules, and stored procedures can be supported, making it easier to query for complex and SQL queries that need to optimize performance.

Core components

The core components are mainly the following:

    • Sqlsessionfactorybuilder: Generates sqlsessionfactory based on configuration information or code;
    • Sqlsessionfactory: Rely on the factory to generate sqlsession;
    • Sqlsession: is an interface that can send SQL to execute and return results, or get mapper;
    • SQL Mapper: is a newly designed component of MyBatis, consisting of a Java interface and an XML file that requires the corresponding SQL and mapping rules. It is responsible for sending SQL to execute and returning the result.
Build Sqlsessionfactory

Each MyBatis application is centered on an instance of Sqlsessionfactory, and its task is to create a sqlsession. Sqlsesion is similar to a JDBC Connection object.

There are 2 ways to create Sqlsessionfactory: One is the way XML is configured, one is the way code is, and the XML configuration is recommended.

Define the Mybatis-config.xml file 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 aliases-- <typeAliases> <typealias alias= "role" type= "Com.learn.chapter2.po.Role"/> </typeAliases> <!-- Define database information. Default build environment with development database--<environments default= "Development" > <environment id= "Development"            > <!--with 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 Mapper--<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, playing the role of the façade, the real work is the executor interface. You need to ensure that you close it properly every time you run out.

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

A mapper consists of a Java interface and an XML file (or annotation) that functions as follows:

    • Defining parameter types
    • Description Cache
    • Describing SQL statements
    • Defining mapping relationships for query results and Pojo

First, define the Java interface:

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

Then, define the mapping 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 definition of Pojo object role is relatively simple and is not listed. #{id} for this SQL parameter, the alias of the SQL column and the property name of the Pojo are consistent, and the query results of the statement are automatically mapped to the role attribute, which is the automatic mapping.

Execute Query

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

Sqlsessionfactory in the entire life cycle of mybatis applications, each database corresponds to only one sqlsessionfactory, and a tool class can be implemented to obtain the object in a singleton mode.

The life cycle of the sqlsession is a thread insecure object that is in the process of requesting a database to process transactions, especially when it comes to multithreading. It survives the request and operation of an application and can execute multiple SQL to ensure transactional consistency.

Mapper's role is to send SQL, then return the desired result, or execute SQL to modify the database's data, so it should be within a sqlsession transaction method, like the execution of a SQL statement in JDBC, its maximum scope and sqlsession are the same.

The overall structure of the book

This book is divided into 3 parts, in turn, introduced the basic application of mybatis, principle and plug-in development, practical application.

Basic applications

Mainly describes how to use MyBatis effectively:

    • MyBatis characteristics
    • Core components and their life cycle
    • MyBatis Configuration
    • Mapper
    • Dynamic SQL
MyBatis principle

Deep source understanding of the internal workings of MyBatis and plug-in development methods and techniques:

    • This paper introduces the analysis and operation Principle of MyBatis, and will understand how the sqlsession is constructed and how the four objects work.
    • Introducing the MyBatis Plugin
Actual application

It mainly explains some practical scenes of MyBatis:

    • Introducing Mybatis-spring, explaining how to integrate MyBatis applications in Spring projects
    • Introduce the practical scenarios of MyBatis, select some typical scenarios, and resolve some errors and performance losses that developers need to avoid in each scenario.

The next chapter describes MyBatis configuration, better configuration of MyBatis for different business scenarios, and the extensions that are available to us.

Introduction to MYBATIS:JDBC and MyBatis in layman's

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.