MyBatis--Quick Start

Source: Internet
Author: User

What is MyBatis?
MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of the result set. MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plan Oldjava Objects, ordinary Java objects) to records in a database.

each one MyBatis applications are all based on a sqlsessionfactory the instance of the object is core. sqlsessionfactory can be obtained by Sqlsessionfactorybuilder objects, Sqlsessionfactorybuilder objects can be derived from an XML configuration file, Or build the Sqlsessionfactory object from an instance of the configuration class.


Create Sqlsessionfactory from XML

The XML configuration file contains the core settings for the MyBatis system, including the data source that gets the instance of the database connection and The transaction manager that determines the scope and control of the transaction.

Instance:

<?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><!--Configuring environment variables--><environments default= "development" ><!-- The environment element Body contains the environment configuration for transaction management and connection pooling--><environment id= "development" ><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><!--configuration mappers--><!-- The mappers element is a list of all mapper (mappers), mapper XML files that contain SQL code and map definition information--><mappers><mapper resource= "org/mybatis/ Example/blogmapper.xml "/></mappers></configuration>


The Sqlsessionfactory object is created by Sqlsessionfactorybuilder.

Its main function is to create sqlsession objects, like Sqlsessionfactorybuilder objects, there is no need to create a sqlsessionfactory every time you access mybatis, it is common practice to create a global object.

Instance:

private static Sqlsessionfactorybuilder Sqlsessionfactorybuilder;  private static Sqlsessionfactory sqlsessionfactory;      private static void Init () throws IOException {String resource = "Mybatis-config.xml";      Reader reader = Resources.getresourceasreader (Resource);      Sqlsessionfactorybuilder = new Sqlsessionfactorybuilder ();  Sqlsessionfactory = Sqlsessionfactorybuilder.build (reader); }


Sqlsession

The primary function of the Sqlsession object is to complete a database access and result mapping. Each thread should have its own sqlsession instance. Instances of sqlsession cannot be shared and threads are unsafe . The best range is therefore the request or method scope. You must never place a reference to a sqlsession instance in a static field of a class or even in an instance field. It is also never possible to place references to sqlsession instances in any type of management scope, such as HttpSession in the Serlvet schema.

It is important to close the session, and you should make sure that you use the finally block to close it. The following example is a basic pattern to ensure that sqlsession is closed:


sqlsession session = Sqlsessionfactory.opensession (); try {      Blogmapper mapper = Session.getmapper (blogmapper.class );      Blog blog = mapper.selectblog (101);} finally {      session.close ();}

Mapper Instances

What exactly did you do with sqlsession and Mapper objects? (the mapped SQL statement is critical)

Let's start by looking at:

statements can be defined by XML or annotations, let's take a look at XML

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Org.mybatis.example.BlogMapper" ><select id= "Selectblog" parametertype= "int" resulttype= " Blog ">select * from blog where id = #{id}</select>        </mapper>


Package org.mybatis.example;//Interface Public interface Blogmapper {Blog selectblog (int id);} Operation execution Sqlsession session = Sqlsessionfactory.opensession (); try {//getmapper gets mapper object Blogmapper mapper = Session.getmapper (Blogmapper.class); Blog blog = mapper.selectblog (101);} finally {session.close ();}

Let's take a look at how to use Java annotation to replace the write-map statement. XML

use annotations more clearly, but for complex SQL It's going to be messy, for complex SQL Recommended Use XML


Package Org.mybatis.example;public interface Blogmapper {@Select ("select * FROM blog WHERE id = #{id}") Blog selectblog (int ID);}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MyBatis--Quick Start

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.