MyBatis Getting Started

Source: Internet
Author: User

First, what is MyBatis

You can simply interpret MyBatis as an upgraded version of Ibatis, a Java persistence layer framework that relies on the JDBC interface, which contains SQL maps and data Access objects components. MyBatis can be used to configure the original mapping through XML or annotations, mapping interfaces and Java Pojo to records in the database.

Second, how to configure MyBatis

Development environment: WIN10 64-bit English version, sql2008r2,eclipse4.4,jdk1.7 latest version number, mavne3.2.1

Jar Package Version: mybatis3.2.6,sqljdbc4-4.0,log4j-1.2.17, junit-4.11 (optional)

Step: 1. Create a new Mavne project in Eclipse, select Maven-archetype-quickstart, select Next, and enter the project name in the new window Artifactid.

2. Add the jar package dependency in Pom.xml, as follows:

<Dependencies>    <Dependency>            <groupId>Junit</groupId>            <Artifactid>Junit</Artifactid>            <version>4.11</version>            <!--It is introduced at the time of development and is not loaded when it is released. -            <Scope>Test</Scope>        </Dependency>                <!--MyBatis Core Pack -        <Dependency>            <groupId>Org.mybatis</groupId>            <Artifactid>MyBatis</Artifactid>            <version>3.2.6</version>        </Dependency>                <!--Import SQL Server database link jar Package -        <Dependency>        <groupId>Com.microsoft.sqlserver</groupId>        <Artifactid>Sqljdbc4</Artifactid>        <version>4.0</version>            </Dependency>      </Dependencies>

3, in the project Src/main/java this source folder to create a new mybatis configuration file, 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>    <!--Note: Each label must be written sequentially, or the egg-sore DTD will indicate an error: The content of element type "configuration" must match "(Properties?,settings?,ty Pealiases?,typehandlers?,objectfactory?,objectwrapperfactory?,plugins?,environments?,mappers?) ". -    <!--Database Files -    <PropertiesResource= "Db.properties" />    <!--Environment Development mode work mode -    <Environmentsdefault= "Work">        <EnvironmentID= "Work">            <TransactionManagertype= "JDBC" />            <DataSourcetype= "Pooled">                < Propertyname= "Driver"value= "${driver}" />                < Propertyname= "url"value= "${url}" />                < Propertyname= "username"value= "${username}" />                < Propertyname= "Password"value= "${password}" />            </DataSource>        </Environment>    </Environments>    <!--registering a mapping file -    <mappers>        <!--Mapping by XML -        <MapperResource= "Com/mybatis/demo/usermapper.xml" />        <!--map by annotated way -><Mapperclass= "Com.mybatis.demo.IUserMapper" />
    </ mappers > </ Configuration >

4, in the third step notice the <properties resource= "Db.properties"/> This, so write is to separate the database connection string in a Db.properties file, as follows:

Driver = Com.microsoft.sqlserver.jdbc.SQLServerDriverurl =jdbc:sqlserver://localhost:1433;databasename= Dbtestusername =sapassword =      //The password here is empty

Here, by adding the jar dependency in the pom.xml, adding MyBatis to the Code folder to access the database configuration information, and self-mapping information, A new db.properties holds the database connection string information, and a basic MyBatis test project is built up, such as

    

Third, create a simple select query

1, create a new database in sql2008 dbtest, create a new table in the users, inside 3 fields Id,name,age

2. Create a new Pojo object for users.

3. Mapping data by XML

Create a new Usermapper.xml mapping file below the current package

<?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 "><Mappernamespace= "Com.mybatis.demo.userMapper">    <!--get a User object based on ID query -    <SelectID= "GetUser"ParameterType= "int"Resulttype= "Com.mybatis.demo.User"Resultmap= "UserMap">SELECT * from Users where id_id=#{id}</Select>    <Resultmaptype= "Com.mybatis.demo.User"ID= "UserMap">        <!--ID for primary key -        <ID Property= "id"column= "id_id" />        <!--result for a field other than the primary key -        <!--If column is incorrectly written, the return value is the type default value <result property= "name" column= "name_s"/> -        <result Property= "Name"column= "Name_n" />          <result Property= "Age"column= "Age_a" />    </Resultmap></Mapper>

4. Map data by annotation method

Create a new Iusermapper interface below the current package

 PackageCom.mybatis.demo;ImportOrg.apache.ibatis.annotations.Result;ImportOrg.apache.ibatis.annotations.Results;ImportOrg.apache.ibatis.annotations.Select;ImportCom.mybatis.demo.*; Public Interfaceiusermapper {@Select ("SELECT * from Users where id_id =#{id}") @Results ({@Result ( property= "id", column= "id_id"), @Result ( property= "Name", column= "Name_n"), @Result ( property= "Age", column= "Age_a") })     PublicUser GetById (intID);}
 
5. Create a new test class
 PackageCom.mybatis.demo;Importjava.io.IOException;ImportJava.io.InputStream;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder; Public classTest { Public Static voidMain (string[] args)throwsIOException {//1. Load configuration fileString resource = "Conf.xml"; InputStream InputStream= Test.class. getClassLoader (). getResourceAsStream (Resource); //2, the construction of Sqlsession factorySqlsessionfactory sessionfactory =NewSqlsessionfactorybuilder (). Build (InputStream); //3. Create a sqlsession that can execute SQL in the mapping filesqlsession session =sessionfactory.opensession (); //4. Mapping SQL identification StringString statement = "Com.mybatis.demo.userMapper.getUser"; //5. Execute QueryUser user1 = Session.selectone (statement, 56); System.out.println ("XML way:" +user1); Iusermapper Usermapper= Session.getmapper (iusermapper.class); User User2= Usermapper.getbyid (56); System.out.println ("Annotation Method:" +user2); //6. Close Session ObjectSession.close (); }}

6, need to pay attention to a few places

    

MyBatis Getting Started

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.