MyBatis Introductory Learning Tutorial (i)-mybatis QuickStart _java

Source: Internet
Author: User
Tags create database

MyBatis is an open source project for Apache Ibatis, the project was migrated from Apache Software Foundation to Google code in 2010 and renamed MyBatis. November 2013 migrated to GitHub.

The word ibatis is derived from the combination of "Internet" and "Abatis", a Java-based persistence layer framework. The persistence layer framework provided by Ibatis includes SQL maps and Data Access Objects (DAO)

First of all, to introduce the meaning of 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 encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java Pojo (Plain old Java Objects, normal Java objects) to records in the database.

Second, MyBatis Quick Start

2.1. Prepare development environment

1. Create a test project, a normal Java project or a Javaweb project, as shown in the following illustration:

  

2, add the appropriate jar package

"MyBatis"

Mybatis-3.1.1.jar

"MySQL driver package"
Mysql-connector-java-5.1.7-bin.jar

   

3, CREATE database and table, for MySQL database

 The SQL script is as follows:

Create database MyBatis;
 Use MyBatis;
 CREATE TABLE users (id int PRIMARY KEY auto_increment, NAME VARCHAR (), age INT);
 INSERT into the users (NAME, age) VALUES (' Aloof pale wolf ');
 INSERT into the users (NAME, age) VALUES (' White Tiger Emperor ',);

Execute the SQL script in the MySQL database, complete the creation of the database and the table, as follows:

  

To this end, the early development of the environmental preparation of all completed.

2.2, the use of MyBatis query table data

1, add the MyBatis profile Conf.xml

Create a conf.xml file in the SRC directory, as shown in the following illustration:

  

  The contents of the Conf.xml file are as follows:

<?xml version= "." Encoding= "utf-"?>
 <! DOCTYPE configuration Public "-//mybatis.org//dtd Config.//en" "Http://mybatis.org/dtd/mybatis--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:/mybatis "/> <property name=" username "value=" "
         root"/> <property name= "password"
         Value= "XDP"/>
       </dataSource>
     </environment>
   </environments>
   
 </ Configuration>

2. Define the entity classes that the table corresponds to, as shown in the following illustration:

  

  The code for the user class is as follows:

Package me.gacl.domain;
 
 /**
  * @author gacl
  * The entity class corresponding to the Users table *
 /public class User {
 
   //Entity class properties and table field name one by one corresponds to
   private int id;< C8/>private String name;
   private int age;
 
   public int getId () {return
     ID;
   }
 
   public void setId (int 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 +"] ";
   }
 }

3. Define SQL mapping files that manipulate the users table Usermapper.xml

Create a me.gacl.mapping package that is designed to hold the SQL mapping file and create a usermapper.xml file in the package as shown in the following illustration:

  

 The contents of the Usermapper.xml file are as follows:

<?xml version= "." Encoding= "utf-"?>
<! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper.//en" "Http://mybatis.org/dtd/mybatis--mapper.dtd" >

<!--specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql mapping file name so that the namespace value is unique

For example namespace= "Me.gacl.mapping.userMapper" is me.gacl.mapping (package name) +usermapper (usermapper.xml file removal suffix)

-->
<mapper namespace= "Me.gacl.mapping.userMapper" >
<!--write the query's SQL statement in the Select tab, set the Select Label ID attribute to the Getuser,id property value must be unique and cannot be duplicated
Use the ParameterType property to indicate the type of parameter to use for the query, Resulttype property indicates the result set type returned by the query
Resulttype= "Me.gacl.domain.User" means that the object that encapsulates the query result into a User class returns
The user class is the entity class that corresponds to the users table
-->

<!--
Get a user object based on ID query
-->

  <select id= "GetUser" parametertype= "int" 
     resulttype= "Me.gacl.domain.User" >
     select * from users where ID =#{id}
   </select>
 </mapper>

4. Register usermapper.xml file in Conf.xml file

 <?xml version= "." Encoding= "utf-"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config.//en" "Http://mybatis.org/dtd/mybatis--config.dtd" > < configuration> <environments default= "Development" > <environment id= "Development" > <trans ActionManager type= "JDBC"/> <!--Configure database connection information--> <datasource type= "Pooled" > <prope Rty name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "Jdbc:mysql://localhost:/myba Tis "/> <property name=" username "value=" root "/> <property name=" password "value=" XDP "/&gt
       ; </dataSource> </environment> </environments> <mappers> <!--registration USERMAPPER.XM L file, Usermapper.xml is located under Me.gacl.mapping This package, so resource written me/gacl/mapping/usermapper.xml--> <mapper resource= " Me/gacl/mapping/usermapper.xml "/> </mappers> </configuration>

5. Write test code: Execute a defined SELECT statement

Create a Test1 class and write the following test code:

Package me.gacl.test;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.Reader;
Import Me.gacl.domain.User;
Import org.apache.ibatis.io.Resources;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;  public class Test {public static void main (string[] args) throws IOException {//mybatis configuration file String resource =
    "Conf.xml";
    Load the MyBatis configuration file with the class loader (it also loads the associated mapping file) InputStream is = Test.class.getClassLoader (). getResourceAsStream (Resource);
    Building Sqlsession Factory Sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). Build (IS); 
    Use the resources provided by MyBatis to load the MyBatis configuration file (It also loads the associated mapping file)//reader Reader = Resources.getresourceasreader (Resource);
    Building Sqlsession Factory//sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). build (reader);
  Create sqlsession sqlsession session = Sessionfactory.opensession () that can execute SQL in the mapping file;  /** * Maps SQL's identity string, * Me.gacl.mapping.userMapper is the value of the namespace attribute of the mapper tag in the Usermapper.xml file, * GetUser is a Select
    The id attribute value of the label, which can be found by the ID attribute value of the select tag to execute SQL/String statement = "Me.gacl.mapping.userMapper.getUser";//Mapping SQL identity string
    The Execute query returns the SQL User user = Session.selectone (statement,) of a unique User object.
  SYSTEM.OUT.PRINTLN (user); }
}

  The results of the implementation are as follows:

  

As you can see from the diagram above, the records in the database have been successfully queried.

The above is the article for the MyBatis Introductory Learning course (i)-mybatis the full content of the QuickStart, I hope to help you.

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.