Introduction to Java Framework---Mybatis

Source: Internet
Author: User

I. Introduction of MyBatis

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

Second, MyBatis work flow(1) Load configuration and initializetrigger Condition: Load configuration fileconfiguration from two places, one is the configuration file, one is the Java code annotations, the SQL configuration information is loaded into a Mappedstatement object (including the incoming parameter mapping configuration, executed SQL statement, result mapping configuration), stored in memory. (2) Receive call requestTrigger Condition: Call the API provided by MyBatisincoming parameters: ID for SQL and incoming parameter objectProcess : Passes the request to the underlying request processing layer for processing. (3) Processing operation request trigger conditions: API interface Layer delivery request come overincoming parameters: ID for SQL and incoming parameter objectprocessing Process:(A) find the corresponding Mappedstatement object based on the SQL ID. (B) parse the Mappedstatement object based on the incoming parameter object to get the final SQL to execute and execute the incoming parameters. (C) obtain a database connection, based on the resulting SQL statements and execute incoming parameters into the database execution, and get the results of the execution. (D) conversion processing of the resulting execution results based on the result mapping configuration in the Mappedstatement object and the resulting processing results. (E) Release the connection resources. (4) The return processing result returns the final processing result. The basic idea of ORM tools

Whether it's used hibernate,mybatis or not, you can have one thing in common:

    • The sessionfactory is obtained from the configuration file (usually in the XML configuration file).
    • Session generated by Sessionfactory
    • In the session to complete the deletion of data and other changes and transaction submissions.
    • Close the session after you are done using it.
    • There is a mapping configuration file between the Java object and the database, usually an XML file.
Functional architecture

MyBatis's functional architecture is divided into three tiers:
    1. API Interface Layer: provides interface APIs for external use, where developers manipulate databases through these local APIs. Once 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 parsing, SQL execution and execution result mapping processing and so on. Its primary purpose is to complete a database operation at the request of the call.
    3. Base Support Layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and caching processing, these are common things, they are extracted as the most basic components. Provides the most basic support for the data processing layer of the upper layer.

More driver packs to add:

Here's a quick start:

The directory is as follows:

Entity class User

 PackageCom.oumyye.model; Public classUser {PrivateString ID; PrivateString name; Private  intAge ;  PublicString getId () {returnID; }     Public voidsetId (String id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; } @Override PublicString 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 "><Mappernamespace= "Com.oumyye.mapping.UserMapping">    <!--To write the query's SQL statement in the Select tab, set the ID property of the Select tag to the Getuser,id property value must be unique and cannot reuse the ParameterType property to indicate the type of parameter used in the query. The Resulttype property indicates that the result set type returned by the query resulttype= "Com.oumyye.model.User" means that the object that encapsulates the query result as a user class returns the user class as the entity class corresponding to the Users table -    <!--get a User object based on ID query -    <SelectID= "GetUser"ParameterType= "String"Resulttype= "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>    <Environmentsdefault= "Development">        <EnvironmentID= "Development">            <TransactionManagertype= "JDBC" />            <!--Configure database connection information -            <DataSourcetype= "Pooled">                < Propertyname= "Driver"value= "Com.mysql.jdbc.Driver" />                < Propertyname= "url"value= "Jdbc:mysql://localhost:3306/mybatis" />                < Propertyname= "username"value= "root" />                < Propertyname= "Password"value= "root" />            </DataSource>        </Environment>    </Environments>    <mappers>               <MapperResource= "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 {@Testpublic void Test () {String resource = "Mybatis.xml"        ;        Use the class loader to load the MyBatis configuration file (It also loads the associated mapping file) InputStream is = Tests.class.getClassLoader (). getResourceAsStream (Resource);               Build Sqlsession factory Sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). Build (IS);        sqlsession session = Sessionfactory.opensession (); /** * Mapping SQL identification String, * com.oumyye.mapping.UserMapping is the value of namespace attribute of mapper tag in Usermapper.xml file, * get User is the id attribute value of the select tag, and the SQL/String statement = "Com.oumyye.mapping.UserMapping.getU" is found by the ID attribute value of the select tag.        Ser ";//Map SQL identifier string//Execute query returns a unique user object for SQL User user = Session.selectone (statement," 1123 "); System.out.priNtln (User.tostring ());}} 

Results:

Introduction to Java Framework---Mybatis

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.