Mybatis+mysql Getting Started with

Source: Internet
Author: User

First, Introduction

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping.

Second, the introduction of the use

1. Add dependencies

A, use MAVEN to manage dependencies, take the version I used this time as an example

    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId> junit</artifactid>            <version>4.12</version>            <scope>test</scope>        </dependency>        <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.  </version>        </dependency>    </dependencies>
View Code

B. You can also use Gradle to manage dependencies

Dependencies {    'junit' 'junit '  4.12 'org.mybatis:mybatis:3.2.3'           'mysql:mysql-connector-java:5.1.38'}
View Code

C, can also go to the official website to download, official address: http://www.mybatis.org/mybatis-3/

2. Initialize database and initial data, take database moy_mybatis and table t_test as an example

# # CREATE DATABASE    moy_mybatis;## create a test table created table t_test (    ID INT (one) auto_increment,     ' creation time '    , ' Modified time ', Content    VARCHAR (COMMENT ' content '),    PRIMARY KEY (id));
View Code

3. New Entity class Testentity

 Packagecom.moy.mybatis3.entity;Importjava.util.Date;/*** [Project]:moy-gradle-project <br/> * [email]:[email protected] <br/> * [DATE]:2018/2/20 <br/> * [Description]: <br/> * *@authorYexiangyang*/ Public classtestentity {PrivateInteger ID; PrivateDate Createtime; PrivateDate Modifytime; PrivateString content;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicDate Getcreatetime () {returnCreatetime; }     Public voidsetcreatetime (Date createtime) { This. Createtime =Createtime; }     PublicDate Getmodifytime () {returnModifytime; }     Public voidsetmodifytime (Date modifytime) { This. Modifytime =Modifytime; }     PublicString getcontent () {returncontent; }     Public voidsetcontent (String content) { This. Content =content; } @Override PublicString toString () {return"testentity{" + "id=" + ID + ", createtime=" + Createtime + ", modifytime=" + Modifytime + ", content= '" + content + ' \ ' + '} '; }}
View Code

4. New Interface Testmapper

 PackageCom.moy.mybatis3.mapper;Importcom.moy.mybatis3.entity.TestEntity;Importjava.io.Serializable;Importjava.util.List;/*** [Project]:moy-gradle-project <br/> * [email]:[email protected] <br/> * [DATE]:2018/2/20 <br/> * [Description]: <br/> * *@authorYexiangyang*/ Public InterfaceTestmapper {List<TestEntity>list ();    Testentity get (Serializable ID); intInsert (testentity testentity); intUpdate (testentity testentity); intDelete (Serializable ID); intcount ();}
View Code

5. New Entity Mapping file Test.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" ><map Per namespace= "Com.moy.mybatis3.mapper.TestMapper" > <select id= "list" resulttype= "Testentity" >SELECT*From t_test</select> <select id= "Count" resulttype= "int" >SELECT Count (*) from T_test</select> <select id= "get" parametertype= "int" resulttype= "testentity" >SELECT Id,create_time as createtime,modify_time as Modifytime, content from T_test WHERE ID=#{id}</select> <insert id= "Insert" parametertype= "testentity" >INSERT into T_test (create_time,modify_time,content) VALUES (#{createtime},#{modifytime},#{content}) </insert> <update id= "Update" parametertype= "Testentity" >UPDATE t_test SET modify_time=#{modifytime},content=#{content} WHERE ID=#{id}</update> <delete id= "delete" parametertype= "int" >DELETE from t_test WHERE ID=#{id}</delete></mapper>
View Code

6. New MyBatis configuration information file 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> < Typealiases> <!--project entity classes corresponding package names--< PackageName= "Com.moy.mybatis3.entity"/> </typeAliases> <!--MYQL database connection information--<environmentsdefault= "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/moy_mybatis?usessl=false"/> <propert Y name= "username" value= "root"/> <property name= "password" value= "123"/> </datasourc E> </environment> </environments> <!--configuring entity mapping XML Paths--<mappers> <mappe R resource= "Mapper/test.xml" ></mapper> </mappers></configuration>
View Code

7, for the convenience of testing, to write a tool to obtain sqlsession class Mybatis3utils

 Packagecom.moy.mybatis3.utils;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder;Importjava.io.IOException;ImportJava.io.Reader;Importjava.util.Objects;/*** [Project]:moy-gradle-project <br/> * [email]:[email protected] <br/> * [Date]:2018/2/19 <br/> * [Description]: <br/> * *@authorYexiangyang*/ Public Abstract classMybatis3utils { Public Static Finalsqlsessionfactory sqlsessionfactory;  Public Static FinalThreadlocal<sqlsession> Sessionthread =NewThreadlocal<>(); Static {        Try{Reader Reader= Resources.getresourceasreader ("Mybatis-config.xml"); Sqlsessionfactory=NewSqlsessionfactorybuilder (). build (reader); } Catch(IOException e) {Throw NewRuntimeException (e); }    }     Public Staticsqlsession getcurrentsqlsession () {sqlsession sqlsession=Sessionthread.get (); if(Objects.isnull (sqlsession)) {sqlsession=sqlsessionfactory.opensession ();        Sessionthread.set (sqlsession); }        returnsqlsession; }     Public Static voidclosecurrentsession () {sqlsession sqlsession=Sessionthread.get (); if(Objects.nonnull (sqlsession)) {sqlsession.close (); } sessionthread.set (NULL); }}
View Code

8, new test class Testmappertest test

 PackageCom.moy.mybatis3.mapper;Importcom.moy.mybatis3.entity.TestEntity;Importcom.moy.mybatis3.utils.Mybatis3Utils;Importorg.apache.ibatis.session.SqlSession;ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.junit.Test;Importjava.util.Arrays;Importjava.util.Date;Importjava.util.List;Import Staticorg.junit.assert.*;/*** [Project]:moy-gradle-project <br/> * [email]:[email protected] <br/> * [DATE]:2018/2/20 <br/> * [Description]: <br/> * *@authorYexiangyang*/ Public classtestmappertest {sqlsession sqlsession;    Testmapper Testmapper; @Before Public voidbefore () {sqlsession=mybatis3utils.getcurrentsqlsession (); Testmapper= Sqlsession.getmapper (testmapper.class); } @After Public voidAfter () {mybatis3utils.closecurrentsession (); } @Test Public voidInsert () {testentity entity=Newtestentity (); Entity.setcreatetime (NewDate ()); Entity.setmodifytime (NewDate ()); Entity.setcontent ("I am Content");        System.out.println (Testmapper.insert (entity));    Sqlsession.commit (); } @Test Public voidcount () {System.out.println (Testmapper.count ()); } @Test Public voidlist () {list<TestEntity> list =testmapper.list ();    System.out.println (Arrays.tostring (List.toarray ())); } @Test Public voidget () {System.out.println (Testmapper.get (1)); } @Test Public voidUpdate () {testentity entity=Newtestentity (); Entity.setid (1); Entity.setmodifytime (NewDate ()); Entity.setcontent ("I am the modified content");        Testmapper.update (entity);    Sqlsession.commit (); } @Test Public voidDelete () {Testmapper.delete (1);    Sqlsession.commit (); }}
View Code

Yexiangyang

[Email protected]

Mybatis+mysql Getting Started with

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.