MyBatis use of demo and cache experience

Source: Internet
Author: User

Below is a simple mybatis using demo.

Overall structure

The overall code is roughly as follows:

Pom dependency

Need to refer to two jar packages, one is MyBatis, the other is Mysql-connector-java, if it is Maven project, add the following dependencies in the Pom.

<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

Build point data for testing in MySQL:

CREATE DATABASE mybatis_test; CREATE TABLE User (age    INTEGER not NULL,    name VARCHAR (+) NOT null DEFAULT '); Insert user values (' Zhanjindong ') Insert user values (' Zhangsan ');

Configuration file

Two types of configuration files are required, one is MyBatis configuration file Mybatis-config.xml, the example is a very simple configuration, detailed configuration on the web with 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 name= "cacheenabled" value= "false"/> <setting name= "Usegeneratedkeys" value= "true"/&G           T <setting name= "Defaultexecutortype" value= "Reuse"/> </settings> <typeAliases> < Typealias alias= "User" type= "Test.mybatis.User"/> </typeAliases> <environments default= "Developmen T "> <environment id=" Development "> <transactionmanager type=" jdbc "/> &lt                 ;d atasource type= "Pooled" > <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "Jdbc:mysql://192.168.71.38:3306/mybatis_test"/&GT              <property name= "username" value= "root"/> <property name= "password" value= "123456"/> </dataSource> </environment> </environments> <mappers> <mappe   R resource= "Mappers/usermapper.xml"/> </mappers> </configuration>

The other is the data provider mapping file: Usermapper.xml in the example. This file is usually located under Src/main/resource or sub-directory 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>  

Corresponding to this mapping file is Test.mybatis under this namespace usermapper this interface, just defines the interface to access 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 of the database is a class called sqlsession, this class is generated through Sqlsessionfactory, general recommendations in the global maintenance of a sqlsessionfactory on it.

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 = Nu    ll    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 ();//must be submitted here, otherwise the data will not go into the database} finally {sqlsession.close ();        }} 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 (); }    }}

Precautions

1, MyBatis will use log4j log, but open debug mode seems to affect the performance very badly.

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

Note : You must add the cache line to the mapper file, otherwise it will not take effect.

Sample code Download

Download the sample code.

Http://www.cnblogs.com/zhanjindong/p/3397828.html

MyBatis use of demo and cache experience

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.