MyBatis Practical Course

Source: Internet
Author: User

Examples from: http://www.yihaomen.com/article/java/302.htm.

what is MyBatis


ORM Tools basic Idea

1. From a configuration file (usually an XML configuration file) Sessionfactory.
3. Perform additions, deletions, and transaction submissions to the session.
4. Close the session after use is complete.
5. There is a mapping configuration file between the Java object and the database, and it is usually an XML file.

The first simple example

First create a data table and insert a record:

Create TABLE ' user ' (  ' id ' int (one) not null auto_increment,  ' userName ' varchar () DEFAULT NULL,  ' Userage ' in T (one) default null,  ' useraddress ' varchar ($) default NULL,  PRIMARY KEY (' id ')) engine=innodb auto_increment=2 DEFAULT Charset=utf8; Insert into ' user ' VALUES (' 1 ', ' Summer ', ' + ', ' shanghai,pudong ');

Set MyBatis configuration file: Configuration.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> <typealias alias= "User" type= "Com.yihaomen.mybatis.model.User"/&gt     ; </typeAliases> <environments default= "Development" > <environment id= "Development" > &lt ; TransactionManager type= "JDBC"/> <datasource type= "Pooled" > <property name= "Driver" Val            Ue= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "Jdbc:mysql://127.0.0.1:3306/mybatis"/>            <property name= "username" value= "root"/> <property name= "password" value= "password"/> </dataSource> </environment> </environments> <mappers> <mapper Reso Urce= "Com/yihaomen/mybatis/model/user.xml"/> </mappers></configuration>

To create the user class:

Package Com.yihaomen.mybatis.model;public class User {private int id;private string username;private string userage; Private String useraddress;        Getters and Setters      } 

Create the user's mapping file in the same directory 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= "Com.yihaomen.mybatis.models.UserMapper" >    <select id= "Selectuserbyid" parametertype= " int "resulttype=" user ">        select * from ' user ' where id = #{id}    </select></mapper>

Finally, create a test class to test the above code:

package Com.yihaomen.test;import Java.io.reader;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 Com.yihaomen.mybatis.model.user;public class Test {private static sqlsessionfactory sqlsessionfactory;private static Reader Reader;static {try {reader = Resources.getresourceasreader ("Configuration.xml"); sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);} catch (Exception e) {e.printstacktrace ();}} public static Sqlsessionfactory GetSession () {return sqlsessionfactory;} public static void Main (string[] args) {sqlsession session = Sqlsessionfactory.opensession (); try {User user = (user) Sessi On.selectone ("Com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1); System.out.println (User.getuseraddress ()); System.out.println (User.getusername ());} finally {session.close ();}}} 

Programming in the form of an interface

First create the Iuseroperation interface:

Package Com.yihaomen.mybatis.inter;import Com.yihaomen.mybatis.model.user;public interface Iuseroperation {        Public User Selectuserbyid (int id);}

Then modify the User.xml to change the namespace to Com.yihaomen.mybatis.inter.IUserOperation:

<?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= "Com.yihaomen.mybatis.inter.IUserOperation" >    <select id= "Selectuserbyid" ParameterType = "int" resulttype= "user" >        select * from ' user ' where id = #{id}    </select></mapper>

Finally, the main method for modifying the test class is as follows:

public static void Main (string[] args) {    sqlsession session = Sqlsessionfactory.opensession ();    try {        iuseroperation useroperation=session.getmapper (iuseroperation.class);        User user = Useroperation.selectuserbyid (1);        System.out.println (User.getuseraddress ());        System.out.println (User.getusername ());    } finally {        session.close ();    }}

To achieve the data increase, delete, change, check

MyBatis Query List

First configure the returned type Resultmap inside the User.xml:

<resultmap type= "User" id= "Resultlistuser" >        <id column= "id" property= "id"/>        <result column= " UserName "property=" UserName "/>        <result column=" userage "property=" Userage "/> <result column=        " UserAddress "property=" useraddress "/> </resultMap>

Then configure the query statement in the User.xml file:

<!--Returns the SELECT statement for list, note that the value of Resultmap is pointed to the previously defined--><select id= "selectusers" parametertype= "string" resultmap= " Resultlistuser ">        select * from user where userName like #{username}</select>

Adding methods in the Iuseroperation interface

Public list<user> selectusers (String userName);    

Finally write the test class:

public void Getuserlist (String userName) {        sqlsession session = Sqlsessionfactory.opensession ();        try {            iuseroperation useroperation=session.getmapper (iuseroperation.class);                       list<user> users = useroperation.selectusers (userName);            for (User user:users) {                System.out.println (User.getid () + ":" +user.getusername () + ":" +user.getuseraddress ());            }                    } finally {            session.close ();        }} public static void Main (string[] args) {        Test testuser=new test ();        Testuser.getuserlist ("%");}

As you can see, the results are queried successfully.

Add Data with MyBatis

Add a method to the Iuseroperation interface:

public void AddUser (user user);

Configure in User.xml:

<!--An SQL statement that performs an increase in operations. The ID and ParameterType are         identical to the name and parameter type of the AddUser method in the Iuseroperation interface, respectively         . Referring to the Name property of the user parameter as #{name}         , MyBatis will use reflection to read         This property of the user parameter. #{name} is case sensitive in name. References to other         properties such as gender are consistent with this. Segeneratedkeys         is set to "true" to indicate that MyBatis gets the primary key generated automatically by the database         ; keyproperty= "id" specifies that the acquired primary key value is injected         into the id attribute of the user-     <insert id= "AddUser" parametertype= "User"         usegeneratedkeys= "true" keyproperty= "id" >         Insert into user (username,userage,useraddress)               values (#{username},#{userage},#{useraddress})      </insert>

Then write the test method in test:

/**     * The test increases, and after the increase, the transaction must be committed, otherwise it will not be written to the database.     *    /public void AddUser () {        user user=new User ();        User.setuseraddress ("People's Square");        User.setusername ("Asuka");        User.setuserage (+);        sqlsession session = Sqlsessionfactory.opensession ();        try {            iuseroperation useroperation=session.getmapper (iuseroperation.class);            Useroperation.adduser (user);            Session.commit ();            System.out.println ("the currently added user ID is:" +user.getid ());        } finally {            session.close ();        }    }

Update data with MyBatis

method, add the method to Iuseroperation first:

public void UpdateUser (user user);

Then configure User.xml:

<update id= "UpdateUser" parametertype= "user" >        update user set Username=#{username},userage=#{userage}, Useraddress=#{useraddress} where Id=#{id}    </update>

Add test methods:

public void UpdateUser () {        //Get user First, then modify, commit.        sqlsession session = Sqlsessionfactory.opensession ();        try {            iuseroperation useroperation=session.getmapper (iuseroperation.class);            User user = Useroperation.selectuserbyid (4);                        User.setuseraddress ("The original Pudong Innovation Park of the Magic");            Useroperation.updateuser (user);            Session.commit ();                    } finally {            session.close ();        }    }

Delete Data with MyBatis

Similarly, the iuseroperation increase method:

public void deleteuser (int id);

Configuration user.xml:

<delete id= "DeleteUser" parametertype= "int" >        delete from user where Id=#{id}    </delete>

Write a test method in the test class:

  /**     * Delete data, delete must commit.     * @param ID */public    void deleteuser (int id) {        sqlsession session = Sqlsessionfactory.opensession ();        try {            iuseroperation useroperation=session.getmapper (iuseroperation.class);                       Useroperation.deleteuser (ID);            Session.commit ();                    } finally {            session.close ();        }    }

In this way, all additions and deletions are completed, notice in addition, change, delete the time to call Session.commit (), so that the database will actually operate, otherwise it is not committed.
So far, simple single-table operation, it should be, the next time, I will talk about multi-table union query, as well as the selection of the result set.

Query that implements the associated data

With the basis of the previous chapters, some simple applications can be processed, but in the actual project, is often related to the table query, such as the most common to a multi-pair, one-to-many. How these queries are handled is a matter of speaking. We first create a article this table and initialize the data.

Drop TABLE IF EXISTS ' article '; Create TABLE ' article ' (  ' id ' int (one) not null auto_increment,  ' userid ' int (one) ' NOT null,  ' title ' varchar (100 Not NULL,  ' content ' text is not NULL,  PRIMARY KEY  (' id ')) engine=innodb auto_increment=5 DEFAULT Charset=utf8 --------------------------------add a few test data------------------------------Insert into ' article ' VALUES (' 1 ', ' 1 ', ' Test _title ', ' test_content '); insert INTO ' article ' VALUES (' 2 ', ' 1 ', ' test_title_2 ', ' test_content_2 '); insert INTO ' article ' VALUES (' 3 ', ' 1 ', ' test_title_3 ', ' test_content_3 '); Insert into ' article ' VALUES (' 4 ', ' 1 ', ' test_title_4 ', ' test_content _4 ');

You should find that the corresponding UserID for these articles is 1, so you need to have id=1 data in user tables. Can be modified to meet their own conditions of the data. According to the ORM rule, the table has been created, then it is necessary to have an object corresponding to it, so we add a article class:

Package Com.yihaomen.mybatis.model;public class Article {private int id;private User user;private String title;private St Ring Content;public int GetId () {return ID;} public void setId (int id) {this.id = ID;} Public User GetUser () {return user;} public void SetUser (user user) {this.user = user;} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;}}

Notice how the user of the article is defined and is a direct definition of a user object. Instead of an int type.

Many-to-one implementations
Scenario: reads all articles published by a user. Of course, it is necessary to configure the SELECT statement inside the User.xml, but the focus is on what data the resultmap of this select corresponds to. This is the point, here to introduce association see the definition as follows:

<!--the configuration of one of the query methods of the User Union article (many-to-one way)--<resultmap id= "Resultuserart Iclelist "type=" com.yihaomen.mybatis.model.Article "; 
 <id property= "id" column= "aid"/> <result p roperty= "title" column= "title"/> <result property= "content" column= "content"/> <associ ation property= "user" javatype= "user" > <id property= "id" column= "id"/> <result property                    = "UserName" column= "UserName"/> <result property= "useraddress" column= "useraddress"/> </association> </resultmap><select id= "getuserarticles" parametertype= "int" resultmap= "ResU Ltuserarticlelist "> select User.id,user.username,user.useraddress,article.id aid,article.title,article.content From User,article where User.id=article.userid and User.id=#{id} </select>  

Once this is configured, it is possible to combine the SELECT statement with the mapping of the resultmap to see. Use Association to get the associated user, this is a many-to-one situation, because all the articles are the same user.

There is another way to reuse the resultmap we've defined earlier, and we've defined a resultlistuser to see how this second approach is implemented:

<resultmap type= "User" id= "Resultlistuser" >        <id column= "id" property= "id"/>        <result column= " UserName "property=" UserName "/>        <result column=" userage "property=" Userage "/> <result column=        " UserAddress "property=" useraddress "/>    </resultMap>    <!--User Joint article configuration of Query method two (many-to-one)--        <resultmap id= "resultUserArticleList-2" type= "Com.yihaomen.mybatis.model.Article" >
        <id property= "id" column= "aid"/>        <result property= "title" column= "title"/>        <result property= "Content" column= "content"/>                <association property= "user" javatype= "user" resultmap= "resultlistuser"/ >                 </resultMap>        <select id= "getuserarticles" parametertype= "int" resultmap= " Resultuserarticlelist ">       select User.id,user.username,user.useraddress,article.id aid,article.title, Article.content from User,article               where User.id=article.userid and User.id=#{id}    </select>

In the Iuseroperation interface, join the select corresponding ID name method:

Public list<article> getuserarticles (int id);

Finally write the test method:

public void getuserarticles (int userid) {        sqlsession session = Sqlsessionfactory.opensession ();        try {            iuseroperation useroperation=session.getmapper (iuseroperation.class);                       List<article> articles = Useroperation.getuserarticles (userid);            for (article article:articles) {                System.out.println (article.gettitle () + ":" +article.getcontent () +                        ": Author is:" + Article.getuser (). GetUserName () + ": Address:" +                         Article.getuser (). getuseraddress ());            }        } finally {            session.close ();        }    }

Test passed.

MyBatis Practical Course

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.