MyBatis How to use (a) _java

Source: Internet
Author: User

MyBatis as an ORM lightweight framework to attract countless people's eyeballs, than hibernate to simple and easy to get started, the following start my first MyBatis program.

First, download the MyBatis package

We know that any frame will have its package, we download its package from its official website, the website is: http://www.mybatis.org/mybatis-3/, I use this version 3.3.0. After the download is complete, unpack to see the following directory structure:

Mybatis-3.3.0.jar is its package, the Lib directory is its dependency package, we put these packages into our project. I created here is the Javaweb project, convenient to do the Web test later, write the program is a normal Java program.

Second, configure the environment

After putting the MyBatis package into the project's Lib directory, and then configuring the MyBatis environment, we know that MyBatis is an ORM framework, a DAO layer in development, and a database, so we have to have data, here, for example, MySQL data, The specific build and build tables are not elaborated here.

In the SRC directory to create a mybatis configuration file, the filename is called: Configuratin.xml, the contents of the file are as follows:

 <?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> <!--alias--> <typeAliases> <typealias alias= "message" type= " Com.cn.imooc.entity.Message "/> </typeAliases> <environments default=" 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/weixin? Useunicode=true&characterencoding=utf-8 "/> <property name= username" value= "root"/> <property "Password" value= "123456"/> </dataSource> </environment> </environments> <!--mapping file--> < 
mappers> <mapper resource= "Com/cn/mappers/message.xml"/> </mappers> </configuration> 

There are a number of configuration items in the MyBatis configuration file that only use these few,

<typeAliases> alias configuration, that is, to alias entity classes, in order to use the entity classes in the mapping file without using the full class name, but using aliases, play a simple role

<environments> configured a number of environments, such as data configuration, where we configured the data source

<mappers> configuration mapping file, where Message.xml mapping files are configured under the Com.cn.mappers package

The following is a description of the message entity class, which is a property in this entity class, as follows,

Package com.cn.imooc.entity;
public class Message {
private String ID;
Private String command;
Private String description;
private String comment;
Public String GetId () {return
ID;
}
public void SetId (String id) {
this.id = ID;
}
Public String GetCommand () {return
command;
}
public void SetCommand (String command) {
this.command = command;
}
Public String GetDescription () {return
description;
}
public void SetDescription (String description) {
this.description = description;
}
Public String getcomment () {return
comment;
}
public void Setcomment (String comment) {
this.comment = comment;
}
@Override public
String toString () {return
"message [id=" + ID + ", command=" + Command + ", description=" 
   
    + description + ", comment=" + comment + "]";
}

   

Provides the getxxx and Setxxx methods, where the Setxxx method is critical, I have the properties and the database field name is consistent, you can easily use MyBatis query results after reflection into the entity class, of course, and the database table field name inconsistent, follow up to explain.

The Message.xml mapping file is as follows,

<mapper namespace= "Com.cn.inter.IMessageOperation" >
<select id= "Selectuserbyid" parametertype= "int" Resulttype= "Com.cn.imooc.entity.Message" >
select * from ' message ' WHERE id = #{id}
</select>
<select id= "selectmessages" resulttype= "message" >
select ID,
command,
description,
comment From message
;
</select>
</mapper>

This is my mapper mapping file, there are two methods, one is: Selectuserbyid based on ID query, the other is selectmessages query all

OK, so far, our mybatis environment has been built, and the following can be tested.

Third, testing

Here is the test code,

 package com.cn.test; import java.io.IOException; import java.io.Reader; Import Org.apac
He.ibatis.io.Resources;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;
Import Com.cn.imooc.entity.Message;
public class MyTest {public static void main (string[] args) {//TODO auto-generated method stub reader reader;
Sqlsession Sqlsession=null;
try {//1, get sqlsessionfactory reader = Resources.getresourceasreader ("Configuration.xml");
Sqlsessionfactory sqlsessionfactory=new Sqlsessionfactorybuilder (). build (reader);
2, obtain sqlsession sqlsession=sqlsessionfactory.opensession ();
3, Query message Message=sqlsession.selectone ("Com.cn.inter.IMessageOperation.selectUserByID", 1);
SYSTEM.OUT.PRINTLN (message);
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();} finally{Sqlsession.close ();}} }

As you can see from the above, you first need a sqlsessionfactory, and then by Sqlsessionfactory to get sqlsession, executed by the sqlsession query, using the SelectOne method, The first parameter is the namespace+ "." In the mapping file. Method name, and the second parameter is the query parameter.

The above is a small set to introduce the MyBatis how to use (a) all the narrative, I hope to help you. Follow-up will also introduce other versions, more content please pay attention to cloud habitat community!

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.