Detailed Java based on MyBatis usage example _java

Source: Internet
Author: User

MyBatis predecessor called Ibatis, this is an open source project Apache, 2010 This project by the Apache Software Foundation migrated to Google Code, and renamed 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 of result sets. MyBatis uses simple XML or annotations for configuration and raw mappings, mapping interfaces and Java POJOs (the plan old Java Objects, normal Java objects) to records in the database.

MyBatis's functional architecture is divided into three layers (Pictures borrowed from Baidu Encyclopedia):

1 API Interface layer: provided to external use 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 specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing. Its main purpose is to complete a database operation based on the call request.

3 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 are extracted as the most basic components. Provide the most basic support for the upper layer of data processing.

Here is a simple mybatis use demo.
Overall structure

Pom dependency

Need to refer to two jar packages, one is MyBatis, the other is Mysql-connector-java, if it is Maven project, the POM can add dependencies as follows.

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactid>mybatis</artifactid >
  <version>3.2.3</version>
</dependency>
<dependency>
  <groupid >mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version> 5.1.26</version>
</dependency>

Data preparation

Create data for testing in MySQL:

CREATE DATABASE mybatis_test;

CREATE TABLE user
(not
  null for age INTEGER,
  name VARCHAR (=) NOT null DEFAULT "

);

Insert user values (' Zhanjindong ');
Insert user values (' Zhangsan ');

Configuration file

Two types of configuration files are required, one is the MyBatis configuration file Mybatis-config.xml, the example is a very simple configuration, detailed configuration on the web there are a lot of instructions.

<?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> <settings> <!--changes from the defaults for testing--> <setting NA Me= "cacheenabled" value= "false"/> <setting name= "Usegeneratedkeys" value= "true"/> <setting name= "Defaultexecutortype" value= "Reuse"/> </settings> <typeAliases> <typealias alias= "User" t  Ype= "Test.mybatis.User"/> </typeAliases> <environments default= "Development" > <environment Id= "Development" > <transactionmanager type= "jdbc"/> <datasource type= "pooled" > &L T;property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "jdbc:mysql://192.168.7  1.38:3306/mybatis_test "/> <property name=" username "value=" "Root"/>
       <property name= "Password" value= "123456"/> </dataSource> </environment> </e nvironments> <mappers> <mapper resource= "Mappers/usermapper.xml"/> </mappers> </c
 Onfiguration>

The other is the data Access interface mapping file: Usermapper.xml in the example. This file is generally located under the Src/main/resource or under the subdirectory MyBatis can be found, in Mybatis-config.xml by the Mappers/mapper node resource specified.

<?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= "Test.mybatis.UserMapper" >
  <!--here namespace must be the path to the Usermapper interface "-->
  <insert id= "Insertuser" parametertype= "user" >
    insert INTO User (name,age) VALUES (#{name},#{age})
    <!--There is no semicolon at the end of SQL, otherwise the ORA-00911 error-->
  </insert>

  <!--The ID must be the same as the interface method name in the Usermapper interface- >
  <select id= "GetUser" resulttype= "User" parametertype= "java.lang.String" >
    select * from User Where Name=#{name}
  </select>
</mapper>

The mapping file corresponds to the Usermapper interface under the Test.mybatis namespace, but defines the interface that accesses the data table:

Package test.mybatis;

Public interface Usermapper {public
  void Insertuser (user user);

  Public User GetUser (String name);
}

Need a POJO:User.java

Package test.mybatis;

public class User {
  private String name;
  Private Integer age;

  Public String GetName () {return
    name;
  }

  public void SetName (String name) {
    this.name = name;
  }

  Public Integer Getage () {return age
    ;
  }

  public void Setage (Integer age) {
    this.age = age;
  }

  Public User (String name, Integer age) {
    super ();
    this.name = name;
    This.age = age;
  }

  Public User () {
    super ();
  }
}

Test

Through the MyBatis operation database is used a class called sqlsession, this class is generated through the sqlsessionfactory, generally recommended in the global maintenance of a sqlsessionfactory can be.

Testmybatis.java

Package test.mybatis;

Import java.io.IOException;
Import Java.io.Reader;

Import org.apache.ibatis.io.Resources;
Import org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Mybatisutil {
  private final static sqlsessionfactory sqlsessionfactory;
  static {
    String resource = ' mybatis-config.xml ';
    Reader reader = null;
    try {
      reader = Resources.getresourceasreader (Resource);
    } catch (IOException e) {
      System.out.println ( E.getmessage ());

    }
    Sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);

  public static Sqlsessionfactory Getsqlsessionfactory () {return
    sqlsessionfactory;
  }
}

The test code is as follows:

Testmybatis.java

Package test.mybatis;
Import org.apache.ibatis.session.SqlSession;

Import Org.apache.ibatis.session.SqlSessionFactory;
  public class Testmybatis {static sqlsessionfactory sqlsessionfactory = null;
  static {sqlsessionfactory = Mybatisutil.getsqlsessionfactory ();
    public static void Main (string[] args) {testadd ();
  GetUser ();
    public static void Testadd () {sqlsession sqlsession = sqlsessionfactory.opensession ();
      try {usermapper usermapper = Sqlsession.getmapper (Usermapper.class);
      User user = New User ("Lisi", New Integer (25));
      Usermapper.insertuser (user);
    Sqlsession.commit ();//Here must be submitted, otherwise the data will not go into the database} finally {sqlsession.close ();
    The public static void GetUser () {sqlsession sqlsession = sqlsessionfactory.opensession ();
      try {usermapper usermapper = Sqlsession.getmapper (Usermapper.class);
      User user = Usermapper.getuser ("Zhangsan"); System.out.println ("Name:" + user.getname () + "|aGE: "+ user.getage ());
    finally {sqlsession.close ();

 }
  }
}

Attention matters

1, MyBatis will use log4j log, but turn on the debug mode seems to have a very strong performance impact.

2, MyBatis query cache has a very large impact on performance, enabling and not enabling a very wide gap

Note: Mapper file must add cache this line, otherwise not effective.

Sample Code Downloads: Code Downloads

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.