English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MyBatis Framework Beginner Learning Tutorial

MyBatis is an excellent persistence framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates almost all JDBC code and manual parameter setting, as well as the encapsulation of result set retrieval. MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects, ordinary Java objects) to records in the database.

1Create the project and import the jar packages

   You can create a Java project or a web project, then import the mybatis jar package and dependency packages as well as the database jar package. I use Oracle personally.10g database

   mybatis-3.2.2.jar Core driver

   asm-3.3.1.jar
   cglib-2.2.2.jar
   commons-logging-1.1.1.jar
   javassist-3.17.1-GA.jar
   log4j-1.2.17.jar
   slf4j-api-1.7.5.jar
   slf4j-log4j12-1.7.5.jar
   classes12.jar Oracle10g's jar package

2Create the core configuration file sqlMapConfig.xml for connecting to the database

    Create a sqlMapConfig.xml file under the src directory

<?xml version="1.0" encoding="UTF-8" &63;>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <!--Configure data source, environment-->
  <!--Multiple environments can be configured, one for testing and one for production-->
  <environments default="test">
    <!--Test environment-->
    <environment id="test">
      <!--Configure transaction: JDBC transaction/MANAGED transaction handed over to the container-->
      <transactionManager type="JDBC"></transactionManager>
      <!--DataSource: POOLED pooled/UNPOOLED non-pooled/JNDI password encryption, high security-->
      <dataSource type="POOLED">
        <property name="driver" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="scott"/>
        <property name="password" value="luogg"/>
      </dataSource>
    </environment>
    <!--Server environment-->
    <environment id="deploy">
      <transactionManager type="JDBC"></transactionManager>
      <dataSource type="POOLED">
        <property name="driver" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="scott"/>
        <property name="password" value="luogg"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/luogg/mapper/PersonMapper.xml"/>
  </mappers>
</configuration>

3Create a test folder under src, and create a TestMybatis.java file under the test folder

package test;
import com.luogg.domain.Person;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 * Created by luogg on 2017/2/17.
 */
public class TestMybatis {
  @Test
  public void init() throws IOException {
    /**
     * Test the database connection
     * 1.Define a String type variable resource, pointing to the xml file configured to connect to the database
     * 2.Create an input stream to read our database configuration file
     * 3.Create a factory with the input stream
     * 4.Open the factory after having the factory
     */
    String resource = "sqlMapConfig.xml";
    InputStream is = Resources.getResourceAsStream(resource);
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
    SqlSession session = factory.openSession();
}

At this point, we can perform unit tests to see if a session has been created, green indicates success, so we will next create a database table and write SQL statements

4Create a database and write data

CREATE TABLE person(
   ID NUMBER(2),
   NAME VARCHAR2(20),
   sex NUMBER(2),
   age NUMBER(3)
)
-- Enter data, click the lock button below, and then click +
SELECT * FROM person FOR UPDATE

5Create a package com.luogg.domain under src, and create a Person.java entity bean under the package

package com.luogg.domain;
/**
 * Created by luogg on 2017/2/17.
 */
public class Person {
  private String name;
  private int sex;
  private int age;
  private int id;
  @Override
  public String toString() {
    return "Person{" +
        "name='" + name + '\'' +
        "sex=" + sex +
        "age=" + age +
        "id=" + id +
        '}';
  }
  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 getSex() {
    return sex;
  }
  public void setSex(int sex) {
    this.sex = sex;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}

6.Create a mapping file corresponding to the database, create a PersonMapper.xml file under the com.luogg.mapper package in the src directory

<?xml version="1.0" encoding="UTF-8" &63;>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--Configure namespace, namespace+ .id is a unique sql statement identifier-->
<mapper namespace="com.luogg.mapper.PersonMapper">
  <!--Query all data, parameters have id, resultType result set, parameterType parameter-->
  <!--Note: If there is a collection to be filled in the sql statement, such as querying all data, returning a result set of Person, then the resultType parameter is written directly as the path+Collection type
    For example: If a Person collection is returned, then fill in the path of the Person Bean+Person-->
  <select id="find" resultType="com.luogg.domain.Person">
    SELECT * from person
  </select>
</mapper>

7.Make a mapping in the core configuration file sqlMapConfig.xml to make it recognize our configuration files that have written sql statements

<?xml version="1.0" encoding="UTF-8" &63;>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <!--Configure data source, environment-->
  <!--Multiple environments can be configured, one for testing and one for production-->
  <environments default="test">
    <!--Test environment-->
    <environment id="test">
      <!--Configure transaction: JDBC transaction/MANAGED transaction handed over to the container-->
      <transactionManager type="JDBC"></transactionManager>
      <!--DataSource: POOLED pooled/UNPOOLED non-pooled/JNDI password encryption, high security-->
      <dataSource type="POOLED">
        <property name="driver" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="scott"/>
        <property name="password" value="luogg"/>
      </dataSource>
    </environment>
    <!--Server environment-->
    <environment id="deploy">
      <transactionManager type="JDBC"></transactionManager>
      <dataSource type="POOLED">
        <property name="driver" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="scott"/>
        <property name="password" value="luogg"/>
      </dataSource>
    </environment>
  </environments>
  <!--Mapping file mapper-->
  <mappers>
    <mapper resource="com/luogg/mapper/PersonMapper.xml"/>
  </mappers>
</configuration>

8.Return the result set by accessing the sql statement in the configuration file of the TestMybatis.java test class

package test;
import com.luogg.domain.Person;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 * Created by luogg on 2017/2/17.
 */
public class TestMybatis {
  @Test
  public void init() throws IOException {
    /**
     * Test the database connection
     * 1.Define a String type variable resource, pointing to the xml file configured to connect to the database
     * 2.Create an input stream to read our database configuration file
     * 3.Create a factory with the input stream
     * 4.Open the factory after having the factory
     * 5.Access the sql statement in the configuration file through session
     */
    String resource = "sqlMapConfig.xml";
    InputStream is = Resources.getResourceAsStream(resource);
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
    SqlSession session = factory.openSession();
    //How to access the sql statement in PersonMapper.xml?63; Namespace+ .id
    List<Person> list = session.selectList("com.luogg.mapper.PersonMapper.find");
    System.out.println(list.size());
    for(Person p : list){
      System.out.println(p);
    }
  }
}

Running Result :

The above-mentioned is the mybatis framework入门 learning tutorial introduced by the editor to everyone, hoping it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. Thank you very much for everyone's support for the yells tutorial website!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)