MyBatis--Step by step to teach you to use MyBatis

Source: Internet
Author: User

1, establish the development environment

1.1 Create a project, a Java project, or an Javaweb project,

1.2 Add the required jar package to the project Lib directory

A Mybatis-3.2.4.jar bag

A DRIVER package Mysql-connector-java-5.1.6.jar package

1 . 3 Creating databases and tables

Create Database MyBatis; CREATE TABLE users (id int PRIMARY KEY auto_increment, name VARCHAR (), age INT), INSERT into users (name, age) VALUES (' Guus ', 1); INSERT into users (NAME, age) VALUES (' Guus2 ', 2);
Executionthe above script statement

2. Use MyBatis to query the data in the table

2.1 Add a Mybatis-config.xml configuration file in the project directory

mybatis-config.xml 's 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><environments default= "Development" ><environment id= "development" >< TransactionManager type= "JDBC"/><!--configuration database connection information--><datasource type= "pooled" ><property name= " Driver "value=" Com.mysql.jdbc.Driver "/><property name=" url "value=" Jdbc:mysql://localhost:3306/mybatis "/ ><property name= "username" value= "root"/><property name= "password" value= "/></datasource" ></environment></environments></configuration>

2.2 Defining entities

Code as follows:

Package org.guus.bean;/** *  * Description: User entity * @author Guus * @date August 5, 2015 */public class User {//entity corresponding data table private int ID ;p rivate String name;private int age;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {return "[id =" +this.id+ "  name=" +this.name+ "  age=" +this.age+ "]";}}
2. 3 Define the SQL mapping file for the Users table Usermapper.xml, create a package to hold the SQL mapping file, such as:

usermapper.xml mapping file the contents are as follows:

<?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" ><!-- Specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql the map file name so that the namespace value is guaranteed to be unique--><mapper namespace= " Org.guus.mapping.userMapper "><!--The SQL statement that writes the query in the SELECT tag, set the ID property of the Select tag to getuser,id attribute value must be unique and cannot be duplicated Use the ParameterType property to indicate the type of parameter used in the query, Resulttype property indicates that the result set type returned by the query resulttype= "Org.guus.bean.User" means the object that encapsulates the query result as a User class returns The user class is the entity class corresponding to the Users table--><!--to get a user object--><select id= "GetUser" parametertype= "int" resulttype= "from the ID query Org.guus.bean.User ">select * from users where id=#{id}</select></mapper>
alsoin the mybatis-config.xml configuration file, add the following configuration to register usermapper.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><environments default= "Development" ><environment id= "development" >< TransactionManager type= "JDBC"/><!--configuration database connection information--><datasource type= "pooled" ><property name= " Driver "value=" Com.mysql.jdbc.Driver "/><property name=" url "value=" Jdbc:mysql://localhost:3306/mybatis "/ ><property name= "username" value= "root"/><property name= "password" value= "/></datasource" ></environment></environments><mappers><!--Register Usermapper.xml file, Usermapper.xml is located under Org.guus.mapping This package, so resource written org/guus/mapping/usermapper.xml--><mapper resource= "org/ Guus/mapping/usermapper.xml "/></mappers></configuration>

3, write test class:

Create the test class to execute the SELECT statement, with the following code:

Here's how to get the session to see MyBatis--Quick Start

Package Org.guus.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 Org.guus.bean.user;public class Test {public static void Ma In (string[] args) throws IOException {//Use the ClassLoader to load the MyBatis configuration file (It also loads the associated mapping file) String resource = "Mybatis-config.xml            ";            Reader reader = Resources.getresourceasreader (Resource);            Sqlsessionfactorybuilder Sqlsessionfactorybuilder = new Sqlsessionfactorybuilder ();        Sqlsessionfactory sqlsessionfactory = sqlsessionfactorybuilder.build (reader);        sqlsession session = Sqlsessionfactory.opensession ();          /** * Mapping SQL identification String Org.guus.mapping.userMapper.getUser * GetUser is the id attribute value of the select tag, and the value of the ID property of the Select tag can be found to execute the SQL */String statement = "Org.guus.mapping.userMapper.getUser";//Mapping SQL identification string//executionThe query returns a unique user object for SQL User user = Session.selectone (statement, 1);    System.out.println (User.tostring ()); }}
TestResults:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MyBatis--Step by step to teach you to use MyBatis

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.