MyBatis Getting Started

Source: Internet
Author: User

I. Introduction of MyBatis

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and encapsulates the retrieval of the result set. MyBatis can use simple XML or annotations for configuration and raw mapping, mapping interfaces and Java Pojo (Plain old Java Objects, ordinary Java objects) to records in a database.


mybatis-3.1.1:http://download.csdn.net/detail/huhui_bj/8575253


Ii. Quick Start

2.1 Preparation

First you need to add two jar packages, one is Mybatis-3.1.1.jar and the other is Mysql-connector-java-5.1.7-bin.jar. Then build the database and data tables in MySQL:

Create Database Mybatis;use MyBatis; CREATE TABLE users (id int PRIMARY KEY auto_increment, name VARCHAR (), age INT); INSERT into users (name, age) VALUES (' Tom ' INSERT into-Users (NAME, age) VALUES (' Jack ', 11);

2.2 Add mybatis configuration file Conf.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"/><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= "root"/></datasource></ Environment></environments></configuration>

2.3 Defining the entity classes that the table corresponds to

public class User {private int id;private String name;private int age;    Get,set Method}

2.4 Defining the SQL mapping file that operates on the users table Usermapper.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" > < Mapper namespace= "Com.atguigu.mybatis_test.test1.userMapper" > <select id= "getUser" parametertype= "int" Resulttype= "Com.atguigu.mybatis_test.test1.User" >select * from users where id=#{id}</select></mapper >

2.5 Register the Usermapper.xml file in the Conf.xml file

<mappers><mapper resource= "Com/atguigu/mybatis_test/test1/usermapper.xml"/></mappers>

2.6 Writing test Code

String resource = "Conf.xml"; Load the MyBatis configuration file (It also loads the associated mapping file) Reader reader = Resources.getresourceasreader (Resource); Build Sqlsession factory Sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). build (reader);// Create sqlsessionsqlsession session = Sessionfactory.opensession () that can execute SQL in the mapping file;//Mapping SQL identification string string statement = " Com.atguigu.mybatis.bean.userMapper "+". Selectuser ";//executes a query that returns a unique user object SqlUser user = Session.selectone (statement, 1); SYSTEM.OUT.PRINTLN (user);

Third, crud operation of data table

Implementation of 3.1 XML

<insert id= "Insertuser" parametertype= "Com.atguigu.ibatis.bean.User" >insert into the users (name, age) VALUES (#{ Name}, #{age}), </insert><delete id= "DeleteUser" parametertype= "int" >delete from users where id=#{id}</ Delete><update id= "UpdateUser" parametertype= "Com.atguigu.ibatis.bean.User" >update users set Name=#{name}, Age=#{age} where Id=#{id}</update><select id= "Selectuser" parametertype= "int" resulttype= " Com.atguigu.ibatis.bean.User ">select * from users where Id=#{id}</select><select id=" Selectallusers " Resulttype= "Com.atguigu.ibatis.bean.User" >select * from users</select>

3.2 Implementation of annotations

Public interface Usermapper {@Insert (' Insert into users ' (name, age) VALUES (#{name}, #{age}) ' public int insertuser (User us ER), @Delete ("Delete from Users where Id=#{id}") public int deleteuserbyid (int id), @Update ("Update users set Name=#{name}, Age=#{age} where Id=#{id} ") public int updateUser (user user), @Select (" SELECT * from Users where Id=#{id} ") Public user Getus Erbyid (int id), @Select ("SELECT * from Users"), public list<user> getalluser ();

Register this mapping interface in Conf.xml:

<mapper class= "Com.atguigu.ibatis.crud.ano.UserMapper"/>

Called in the DAO Class:

Public User Getuserbyid (int id) {sqlsession session = Sessionfactory.opensession (); Usermapper mapper = Session.getmapper (Usermapper.class); User user = Mapper.getuserbyid (ID); return user;}

Four, several can optimize the place

4.1 Setting up a database configuration file

# # Db.properties<properties resource= "db.properties"/><property name= "Driver" value= "${driver}"/>< Property name= "url" value= "${url}"/><property name= "username" value= "${username}"/><property name= " Password "value=" ${password} "/>

Then add the configuration for the read db.properties in the MyBatis configuration file Conf.xml:

<!--Introducing resource files--><properties resource= "Db.properties"/>

4.2 Defining aliases for entity classes

<!--Configure an alias for an entity class--><typealiases><!--<typealias type= "Com.mybatis.test1.User" alias= "_user"/>-- ><package name= "Com.mybatis.bean"/> <!--scan this package--></typealiases>
The above configuration simplifies the reference in the SQL mapping XML file, eliminating the need to write the full path of the class every time.


4.3 Add log4j profile, print log information

#log4j. Propertieslog4j.rootlogger=debug, console#consolelog4j.appender.console= org.apache.log4j.consoleappenderlog4j.appender.console.layout= org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=%d [%t]%-5p [%c]-%m% nlog4j.logger.java.sql.resultset=infolog4j.logger.org.apache=infolog4j.logger.java.sql.connection= Debuglog4j.logger.java.sql.statement=debuglog4j.logger.java.sql.preparedstatement=debug



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.