Basics of getting Started with Java MyBatis Framework Basics

Source: Internet
Author: User

First, MyBatis Introduction

MyBatis is a state-of-the-art persistence framework that supports custom SQL, stored procedures, and advanced mappings. MyBatis almost eliminates all JDBC code, and basically does not need to manually set parameters and retrieve results. MyBatis can be configured using simple XML formats or annotations to map basic data elements, map interfaces, and POJOs (normal Java objects) to records in a database.

Second, MyBatis work flow

(1) Load Configuration and initialize

Trigger Condition: Load configuration file

The configuration comes from two places, one is the configuration file, the other is a Java code annotation, the SQL configuration information loaded into a Mappedstatement object (including the incoming parameter mapping configuration, executed SQL statements, result mapping configuration), stored in memory.

(2) Receive call request

Trigger condition: Invoke the API provided by MyBatis

Incoming arguments: ID for SQL and incoming parameter object

Process: Passes the request to the underlying request processing layer for processing.

(3) Processing operation request Trigger condition: API Interface Layer delivery request come over

Incoming arguments: ID for SQL and incoming parameter object

Processing process:

(A) Find the corresponding Mappedstatement object based on the SQL ID.
(B) Parse the Mappedstatement object based on the incoming parameter object, get the final SQL to execute and execute the incoming parameter.
(C) obtain a database connection, execute the database according to the resulting final SQL statement and execute the incoming parameters, and obtain the execution results.
(D) Converting the resulting execution results from the result mapping configuration in the Mappedstatement object and obtaining the final processing results.
(E) Release of connection resources.

(4) Return the processing result to return the final processing result

The basic idea of ORM tools

Whether it's used hibernate,mybatis, you can do it. They have one thing in common:

    • Get sessionfactory from a configuration file (usually an XML configuration file).
    • Session generated by Sessionfactory
    • In the session to complete the data additions and deletions to check and transaction submission.
    • Closes the session after you run out.
    • There is a mapping configuration file between the Java object and the database, and is usually an XML file.

Functional architecture

MyBatis's functional architecture is divided into three tiers:

1, API interface layer: provided to the external use of the interface API, developers through these local APIs to manipulate the database. When the interface layer receives the call request, it invokes the data processing layer to complete the specific data processing.

2, Data Processing layer: Responsible for the specific SQL lookup, SQL resolution, SQL implementation and implementation of the results map processing. Its main purpose is to complete a database operation based on the call request.

3, the basic support layer: responsible for the most basic function support, including connection management, transaction management, configuration loading and caching processing, these are common things, they extracted out as the most basic components. Provide the most basic support for the upper layer of data processing.

Multiple driver packages to add:

Here's a quick start:

The directory is as follows:

Entity class User

Package Com.oumyye.model;

public class User {
  private String ID;
  private String name;
  private int age;
  Public String GetId () {return
    ID;
  }
  public void SetId (String id) {
    this.id = ID;
  }
  Public String GetName () {return
    name;
  }
  public void SetName (String name) {
    this.name = name;
  }
  public int getage () {return age
    ;
  }
  public void Setage (int age) {
    this.age = age;
  }
  @Override public
  String toString () {return
    "User [id= + ID +", name= "+ name +", age= "+ Age +"] ";
  }

}

mapping Files Usermapping.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= "com.oumyye.mapping.UserMapping" >
  <!--write the query's SQL statement in the Select tab, Setting the ID property of the Select label to the Getuser,id property value must be unique and cannot be repeated
  using the ParameterType property to indicate the type of parameter used in the query, and the Resulttype property indicates the result set type
  returned by the query Resulttype= "Com.oumyye.model.User" means that the object that encapsulates the query result into a user class returns
  the user class as the entity class--> the Users table
  <!-- 
    Get a User object
   -->
  <select id= "GetUser" parametertype= "String" 
    resulttype= "based on the ID query Com.oumyye.model.User ">
    select * from User where id=#{id}
  </select>
</mapper>

Resource File Mybatis.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" >
<configuration>
  <environments default= "Development" >
    <environment id= "development" >
      <transactionmanager type= "JDBC"/>
      <!--metabase connection information-->
      <datasource type= "Pooled" >
        <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "
        url" value= "jdbc:mysql:/ /localhost:3306/mybatis "/> <property name=" username "value=" "root"/> <property "name=
        " Password "value=" root "/>
      </dataSource>
    </environment>
  </environments>
  <mappers>

<mapper resource= "Com/oumyye/mapping/usermapping.xml"/>
   </mappers>
</configuration>

Test class:

Package test;

Import Java.io.InputStream;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;

Import Org.junit.Test;

Import Com.oumyye.model.User;
    public class Tests {@Test public void Test () {String resource = "Mybatis.xml";
    Load the MyBatis configuration file with the class loader (it also loads the associated mapping file) InputStream is = Tests.class.getClassLoader (). getResourceAsStream (Resource);

Building Sqlsession Factory Sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). Build (IS);
    sqlsession session = Sessionfactory.opensession (); /** * Maps SQL's identity string, * com.oumyye.mapping.UserMapping is the value of the namespace attribute of the mapper tag in the Usermapper.xml file, * GetUser is Sele The id attribute value of the CT label, which can be found by the ID attribute value of the select tag to execute SQL/String statement = "Com.oumyye.mapping.UserMapping.getUser";//Mapping SQL identity
    string//Execute query returns the SQL User user = Session.selectone (statement, "1123") of a unique User object;
System.out.println (User.tostring ());
 }
}

Results:

The above is about the Java MyBatis Framework Primer Tutorial, I hope to help you learn.

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.