Mybatis3 Simple Introduction

Source: Internet
Author: User

Official website Document: http://mybatis.github.io/mybatis-3/zh/index.html

Source: https://github.com/mybatis/mybatis-3

Maven dependencies:

<dependency>
            <groupId>org.mybatis</groupId>
            <artifactid>mybatis</artifactid >
            <version>3.2.6</version>
</dependency>

No matter which persistence layer framework you use, you first have to have Pojo and DAO

Package Me.poplaris.mybatis.bean;

/**
 * User:poplar
 * date:14-7-4 PM 5:56 * * Public
class User {
  private int id;
  private String name;

  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;
  }
}

Package Me.poplaris.mybatis.dao;

Import Me.poplaris.mybatis.bean.User;

/**
 * User:poplar
 * date:14-7-4 pm 5:59
/public interface Userdao {public
  User getuserid (int id);
}

After we set up Pojo and DAO, we started using MyBatis.

Each MyBatis application is centered on an instance of a Sqlsessionfactory object. An instance of the Sqlsessionfactory object can be obtained through the Sqlsessionfactorybuilder object, and we first introduce the use of XML to build

  @Test public
  void Buildusexml () throws IOException {
//    String resource = "org/mybatis/example/ Mybatis-config.xml ";
    String resource = "Mybatis-config.xml";
    Building sqlsessionfactory
    Reader reader = Resources.getresourceasreader (Resource) from XML;
    Sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);
    Get sqlsession sqlsession session from Sqlsessionfactory
    = Sqlsessionfactory.opensession ();
    try {
      User user = Session.selectone ("Me.poplaris.mybatis.dao.UserDao.getUserId", 1);
    } finally {
      Session.close ();
    }
  
A simple XML configuration file is primarily configured with the data source and transaction manager:

<?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 "/>
            <datasource type=" Pooled ">
                < Property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name=
                "url" value= "jdbc:mysql:// 127.0.0.1:3306/test?autoreconnect=true "/> <property name=" username "value=" "
                root"/>
                < Property name= "Password" value= "123456"/>
            </dataSource>
        </environment>
    </ Environments>
</configuration>

Sometimes you might want to read the data source configuration from properties instead of writing to death in XML. Add Properties configuration to Mybatis-config

<properties resource= "Config.properties" ></properties>
Config.properties files are as follows:

Driver=com.mysql.jdbc.driver
url=jdbc:mysql://127.0.0.1:3306/test?autoreconnect=true
username=root
Password=root

After the modified mybatis-config:

<?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= "config.properties" ></properties>

    < Environments default= "Development" >
        <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>

Execute Buildusexml test, exception occurred

Java.lang.IllegalArgumentException:Mapped Statements collection does not contain value for Me.poplaris.mybatis.dao.UserDao.getUserId
This is because Userdao is not implemented in mapped, and Pojo alias and mappers configuration are added to Mybatis-config.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>     <properties resource=" Config.properties "></ properties>     <typeAliases>         <typealias alias= "User" type= Me.poplari
S.mybatis.bean.user "/>     </typeAliases>     <environments default=" Development ">         <environment id= "Development" >             <transaction Manager type= "JDBC"/>             <datasource type= "pooled" >       & nbsp         <property name= "Driver" value= "${driver}"/>             &N Bsp   <property name= "url" value= "${url}"/>                <property name= "username" value= "${username}"/>                 &LT;P Roperty name= "Password" value= "${password}"/>             </dataSource>   &NB Sp      </environment>     </environments>     <mappers>      
   <mapper resource= "Mybatis/user.xml"/>     </mappers> </configuration>
and implement Userdao, add new XML configuration file User.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= "Me.poplaris.mybatis.dao.UserDao" >
    <select id= "GetUserID" parametertype= "int" Resulttype= "User" >
        select
            *
        from
            ' user '
        where
            id = #{id}
    </select>
</mapper>
The namespace of mapper in User.xml corresponds to the getuserid (int id) method in Userdao for the select operation we defined for the DAO interface class Userdao,id to GetUserID

Execute the Buildusexml test again, print out the normal data, a simple use of XML configuration to read the data successfully implemented.

In the Buildusexml

Session.selectone ("Me.poplaris.mybatis.dao.UserDao.getUserId", 1);
Because we've already configured this namespace in Mapper, this line of code has a simpler and safer way to replace

Userdao Userdao = Session.getmapper (userdao.class);
User user = Userdao.getuserid (1);
So the whole buildusexml test turns out to be this:

  @Test public
  void Buildusexml () throws IOException {
//    String resource = "org/mybatis/example/ Mybatis-config.xml ";
    String resource = "Mybatis-config.xml";
    Building sqlsessionfactory
    Reader reader = Resources.getresourceasreader (Resource) from XML;
    Sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);
    Get sqlsession sqlsession session from Sqlsessionfactory
    = Sqlsessionfactory.opensession ();
    try {
//      User user = Session.selectone ("Me.poplaris.mybatis.dao.UserDao.getUserId", 1);
      Userdao Userdao = Session.getmapper (userdao.class);
      User user = Userdao.getuserid (1);
      SYSTEM.OUT.PRINTLN (user);
    } finally {
      session.close ();
    }
  }

Using XML configuration to implement MyBatis operations has been briefly introduced, more detailed XML configuration, dynamic SQL, etc. can refer to official documentation

The following is an introduction to implementing MyBatis operations without relying on an XML configuration, and the following test method is to use a Java program to create a simple configuration instance

  @Test   public void Builduseanno () {    String url = "Jdbc:mysql://127.0.0.1:3306/test?autoreconnec
T=true ";
    String userName = "root";
    String password = "root";
   //Data source     DataSource DataSource = new Mydefaultdatasource (Url,username,password);
   //Affairs factory     Transactionfactory transactionfactory = new Jdbctransactionfactory ();
    ENVIRONMENT Environment = new Environment ("development", Transactionfactory, DataSource);
    Configuration Configuration = new Configuration (environment);
   //Binding DAO Mapper     Configuration.addmapper (Userdaowithanno.class);
    Sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (configuration);
    Sqlsession session = Sqlsessionfactory.opensession ();      try {      Userdaowithanno Userdao = Session.getmapper (userdaowithanno.class);       Useruser = Userdao.getuserid (1);
      SYSTEM.OUT.PRINTLN (user);
      List<user> userlist = Userdao.getusers ();
      SYSTEM.OUT.PRINTLN (userlist);
    } finally {      session.close ();    }  }
The code fragment that first needs to implement the Datasource,mydefaultdatasource core itself is as follows:

  @Override public
  Connection getconnection (string Username, string password) throws SQLException {
    return Drivermanager.getconnection (Url,username,password);
  }

Run Builduseanno test, exception occurred

Org.apache.ibatis.binding.BindingException:Invalid bound statement (not found): Me.poplaris.mybatis.dao.UserDaoWithAnno.getUserId
This is because the mapper binding is not complete and we need to bind to the specific SQL operation

The main way to configure this is to add a mapping class.

Configuration.addmapper (Userdaowithanno.class);

Mapping classes are Java classes that contain annotations of SQL mapping statements to avoid dependency of XML files

Package Me.poplaris.mybatis.dao;

Import Me.poplaris.mybatis.bean.User;
Import Org.apache.ibatis.annotations.Select;

Import java.util.List;

/**
* User:poplar
* date:14-7-4 PM 5:59 * * Public
interface Userdaowithanno {

@Select ("SELECT *  From user where id= #{id} ") Public
user GetUserID (int id);

@Select (' Select * from user ') public
list<user> getusers ();
}
Complete the registration mapper using the Select annotation, and perform the Builduseanno test again successfully.

OK, the simple use of annotations to complete the MyBatis operation has also been introduced, more comments on the program please refer to the official documents, instance code please click here












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.