How to Use mybatis 1 and mybatis 1

Source: Internet
Author: User

How to Use mybatis 1 and mybatis 1

As a lightweight ORM framework, mybatis attracts the attention of countless people. It is simpler and easier to get started than hibernate. Next I will start my first mybatis program.

1. Download The mybatis package

We know that any framework will have its package. We will download the package from its official website at http://www.mybatis.org/mybatis-3/, and the website I use here is 3.3.0. After the download is complete, decompress the package and you will see the following directory structure:

 

The mybatis-3.3.0.jar is its package, the lib directory is its dependent package, we put these packages in our project. I created a javaweb project to facilitate web Testing in the future. The program is a common java program.

Ii. Configure the environment

Put the mybatis package under the lib directory of the project, and then configure the mybatis environment. We know that mybatis, As An ORM framework, belongs to the DAO layer in development and deals with databases, therefore, we must have data. Here we take mysql Data as an example. The specific database creation and table creation are not described here.

Create a configuration file named configuratin. xml in the src directory. The file content is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configuration PUBLIC "-// mybatis.org//DTD Config 3.0 //" 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 name =" password "value =" 123456 "/> </ dataSource> </environment> </environments> <! -- Ing file -->
<Mappers> <mapper resource = "com/cn/mappers/message. xml"/> </mappers> </configuration>

There are many other configuration items in the mybatis configuration file, which are used only here,

<TypeAliases> alias configuration: This is used to create an alias for an object class. The purpose is to use an alias instead of a full-limit class name in a ing file, which plays a simple role.

<Environments> we have configured some environments, such as data configuration. Here we have configured the data source.

<Mappers> Configure the message ing file. The message. xml ing file under the com.cn. mappers package is configured here.

The following describes the Message object class, which has the following attributes,

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 + "]";    }    }

The getXXX and setXXX methods are provided. The setXXX method is critical. The attributes here are the same as the Field Names of the database. It is convenient to use mybatis to return the results to the object class, of course, it can also be different from the field name of the database table, which will be described later.

The message. xml ing 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 er file. There are two methods in it: selectUserById query based on id, and selectMessages query all

Okay. So far, the mybatis environment has been set up. Now we can test it.

Iii. Test

The following is the test code,

Package com.cn. test; import java. io. IOException; 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.cn. imooc. entity. message; public class MyTest {public static void main (String [] args) {// TODO Auto-generated method stub Reader; SqlSession sqlSession = null; try {// 1. Obtain sqlSessionFactory reader = Resources. getResourceAsReader ("Configuration. xml "); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). build (reader); // 2. Obtain 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 ();}}}

We can see from the above that a SqlSessionFactory is required first, and then sqlSession is obtained by sqlSessionFactory. The sqlSession executes the query and uses the selectOne method. The first parameter is the nameSpace + "in the ing file. "method name. The second parameter is the query parameter.

So far, a mybatis program has been written, and other versions will be introduced in the future.

If you have any mistakes, please correct them.

Thank you.

 

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.