MyBatis Framework Introduction (1)

Source: Internet
Author: User

MyBatis Introduction:

MyBatis is a Java-based persistence layer framework that separates SQL statements from code and is a manifestation of configuration-oriented programming. MyBatis can well support mapping of replicated objects. Apply dynamic SQL technology to avoid assembling SQL statements.

MyBatis Download:

Http://mybatis.github.io/2014/10/11/mybatis-3.2.8-released.html


In the project to the order of the package:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6E/B3/wKiom1WC2JzwH5feAAD0sfLSQG8204.jpg "title=" Qq20150618224103.jpg "alt=" Wkiom1wc2jzwh5feaad0sflsqg8204.jpg "/>

To import the results in the project:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6E/AF/wKioL1WC2qrjX2V3AAHxb1oiGjA659.jpg "title=" Qq20150618224236.jpg "alt=" Wkiol1wc2qrjx2v3aahxb1oigja659.jpg "/>

Post-Import configuration log:

MyBatis SQL statement output is done through the log, so you need to configure the log: The log output level is debug

Log files can be downloaded and modified from the Web:

Log4j.rootlogger=debug, Console #Console log4j.appender.console=org.apache.log4j.consoleappender Log4j.appender.console.layout=org.apache.log4j.patternlayout log4j.appender.console.layout.conversionpattern=%d [%t]%-5p [%c]-%m%n log4j.logger.java.sql.resultset=info log4j.logger.org.apache=info Log4j.logger.java.sql.Connect Ion=debug Log4j.logger.java.sql.statement=debug Log4j.logger.java.sql.preparedstatement=debug



MyBatis Workflow:

    • Read Basic configuration file: Information about the source database

    • Build Sqlsessionfactory: is a sqlsession project that is used to establish a session between the databases

    • Build sqlsession: Execute SQL statement

    • Call MyBatis to provide an API

    • Querying the Map configuration

    • return Result:

    • Close sqlsession


Basic configuration file:

Contains two parts:

    • Connect Database related Information

    • Path location of the map configuration file

<?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" >       </transactionmanager>      <datasource type= "POOLED" >    //whether to use connection pooling         <property name= "Driver"  value= "Com.mysql.jdbc.Driver"/>        <property name = "url"  value= "Jdbc:mysql://localhost:3306/jikebook"/>         <property name= "username"  value= "root"/>  &Nbsp;     <property name= "Password"  value= "* * *"/>       </datasource>    </environment>  </environments >  <mappers>    <mapper resource= "Jike/book/map/jikeUser.xml"/ >  </mappers></configuration>

This file can be downloaded and modified from the Internet


There are several types of map configuration files:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6E/B3/wKiom1WC3Q7ToCqcAAEPgh61BeA483.jpg "title=" Qq20150618230005.jpg "alt=" Wkiom1wc3q7tocqcaaepgh61bea483.jpg "/>


Map file:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/B3/wKiom1WC3YXiAcmXAACOMPFktDA843.jpg "title=" Qq20150618230204.jpg "alt=" Wkiom1wc3yxiacmxaacompfktda843.jpg "/>

The ID here is unique. Resulttype is the return value type. ParameterType is a parameter type


Database Connection code:

String resource = "Jike/book/map/mybatisconfig.xml"; The path of the basic configuration reader reader = null; Stream object Sqlsession session; Execute sqltry {reader = Resources.getresourceasreader (Resource),} catch (IOException e) {//TODO auto-generated catch Blocke . Printstacktrace ();} Sqlsessionfactory sqlmapper = new Sqlsessionfactorybuilder (). build (reader); session = Sqlmapper.opensession (); ...... session.close ();

This piece of code is generic





Use a project to illustrate MyBatis's content.

The entire project was established as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6E/B3/wKiom1WC2mjSVvd5AAFiAUalEW8597.jpg "title=" Qq20150618224513.jpg "alt=" Wkiom1wc2mjsvvd5aafiaualew8597.jpg "/>


New database: Jikebook

Add table Jikeuser to the database:

create database /*!32312 if not exists*/' Jikebook '  /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */; use  ' Jikebook ';/*table structure for table  ' Jikeuser '  */drop table if  EXISTS  ' Jikeuser '; create table  ' Jikeuser '   (   ' id '  int (one)  not null auto_increment,    ' UserName '  varchar ( COLLATE utf8_bin DEFAULT NULL,   ') Password '  varchar ( collate utf8_bin default null,  primary key)   (' id '))  engine=innodb auto_increment=2 default charset=utf8 collate=utf8_bin;/* data for the table  ' jikeuser '  */insert  into  ' jikeuser ' (' id ', ' userName ', ' password ')  values  (1, ' Hello everyone ', NULL); 


Create a new Jikeuser in the Pojo package, add code: Where the variable is consistent with the variable name in the database

Package Jike.book.pojo;public class Jikeuser {private int id;private string username;private string password;public int ge TId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}


config mybatisconfig.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" >       </transactionmanager>      <datasource type= "POOLED" >         <property name= "Driver"  value= " Com.mysql.jdbc.Driver "/>        <property name=" url "  Value= "Jdbc:mysql://localhost:3306/jikebook"/>        <property  name= "username"  value= "root"/>      &nbsP; <property name= "password"  value= "123"/>      </ datasource>    </environment>  </environments>  < Mappers>    <mapper resource= "Jike/book/map/jikeuser.xml"/>  </ Mappers></configuration>


To add a map file:

Jike/book/map/jikeuser.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" ><mapp ER namespace= "/" > <select id= "FindByID" parametertype= "int" resulttype= "Jike.book.pojo.JiKeUser" > select * From Jikeuser where Id=#{id} </select></mapper>


To create a new test class:

package jike.book.test;import java.io.ioexception;import java.io.reader;import  jike.book.pojo.jikeuser;import org.apache.ibatis.io.resources;import  org.apache.ibatis.session.sqlsession;import org.apache.ibatis.session.sqlsessionfactory;import  Org.apache.ibatis.session.sqlsessionfactorybuilder;public class testhello {public static  void main (String[] args)  {// TODO Auto-generated method stub//  Connect database string resource =  "Jike/book/map/mybatisconfig.xml"; reader reader = null; Sqlsession session;try {reader = resources.getresourceasreader (Resource);}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();} Sqlsessionfactory sqlmapper = new sqlsessionfactorybuilder (). build (reader); session =  sqlmapper.opensession ();//jikeuser temp = session. SelectOne ("FindByID",  1); //  The first parameter is the ID of the SQL statement, consistent with the ID configured in the previous XML.   The second is the IdSystem.out.println (Temp.getusername ()) recorded in the database; Session.close ();}}


Geek College: http://www.jikexueyuan.com/course/827.html


MyBatis Framework Introduction (1)

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.