1. Getting Started with MyBatis

Source: Internet
Author: User

MyBatis formerly called IBatis, compared to hibernate is a lightweight ORM framework, the general small project using HIbernate is really overqualified. The two days to learn MyBatis, just a good summary of it.

Let's start with a quick start!

My development environment:

jdk1.8, Windows7, ECLIPSEJ2EE, MySQL, SQLyog


One: MyBatis development environment construction.

1. Construction Projects

Create a new Javaproject and create a new Lib directory to store the required jar packages.

2. Download the required jar package

MyBatis jar Package Click MyBatis in Maven to download

MySQL Database Connection Driver click Mysql-connector Download.

3. Add a jar package

Paste the two jar packages under the new Lib directory, then select the two jar packages, right-click, Build path, add to Path, and add the jar package to the current project.

As follows:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/77/D1/wKioL1Zux4DC1xI3AAAvCIK5SC0004.png "title=" Project.png "alt=" Wkiol1zux4dc1xi3aaavcik5sc0004.png "/>


Second: A simple CRUD to the data table

1. Building a library

CREATE DATABASE MyBatis; Use MyBatis; CREATE TABLE person (id int PRIMARY KEY auto_increment, name VARCHAR (a), age INT), INSERT into person (NAME, age) VALUES (' to M ', +); INSERT into person (name, age) VALUES (' Mike ', +); INSERT into person (name, age) VALUES (' Jack ', 18);

2. Add the MyBatis configuration file Conf.xml

Create a conf.xml file in the SRC directory and add the content, and the connection information needs to be modified by itself.

<?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= "Oracle"/></datasource></ Environment></environments></configuration>

which

①. Default properties for environments and environment specify patterns

Development: Development mode (This is the general choice)

Work: Working mode

②. TransactionManager Type property for specifying transaction manager types
JDBC: Uses the JDBC commit and rollback settings to manage transaction scopes by relying on connections obtained from the data source.

MANAGED: Let a container (such as spring) manage the life cycle of a transaction. The connection is closed by default.

③. DataSource Type property specifies the connection pool types

Unpooled: When the connection is exhausted, it is closed and not placed in the connection pool
Pooled: The connection is exhausted and placed in the connection pool

There is no mention of the connection properties inside.


3. Create a person with the data table corresponding to the entity class

Create a com.mybatis.entities package below SRC to hold the person entity class. The entity class person is then created under the package.

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/77/D2/wKiom1ZuzfayB2JfAACu1B2YeX8678.png "title=" Person.png "alt=" Wkiom1zuzfayb2jfaacu1b2yex8678.png "/>

The specific setter and getter as well as the ToString method are written yourself, and if you add a constructive method with a parameter, be sure to include an argument-free constructor, because MyBatis uses reflection to assign a value to the property.


4. Add the SQL mapping file to manipulate the person data table Personmapper.xml

Create a new Personmapper.xml (class name +mapper.xml) file under the Com.mybatis.entities package and add

The content into the file

<?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.mybatis.entities.PersonMapper" > <!--Find a Perosn object by ID--><select id= "Getperson" parametertype= "int" resulttype= "Com.mybatis.entities.Person" >select * from person WHERE id=#{id}</select> </mapper>

①. The value of the namespace property of the mapper tag is filled in this way:

Personmapper.xml file is located in the package + personmapper.xml remove. xml

is: Com.mybatis.entities.PersonMapper

②. <select> tag is a select query, and if you press Eclipse's prompt key without prompting, the description is not associated. dtd file, associated method Click here in Eclipse how to associate a. dtd file in XML.

③. Properties of the <select> tag

a). ID: We use this when invoking internal SQL statements to ensure that the only one in this file does not conflict.

b). ParameterType: The type of the parameter passed in, because we look up a person object by ID. So it comes in an ID of type int.

c). Resulttype: Return value type, here write the full class name, with the package name.

Internal is the SQL statement, as for #{id} This is used to receive incoming int type number.


5. Associating personmapper.xml mapping files in the Conf.xml file

Use the <mappers> tag to correlate the mapping file. As follows:

<mappers><mapper resource= "Com/mybatis/entities/personmapper.xml"/></mappers>

The <mappers> tag is at the same level as the <environments> tag.


6. Write the test class. Get a Person object

Create a new Com.mybatis.test package and create a Testperson class under the package. Use Junit unit tests to test.

The code is as follows:

import java.io.inputstream;import  org.apache.ibatis.session.sqlsession;import org.apache.ibatis.session.sqlsessionfactory;import  org.apache.ibatis.session.sqlsessionfactorybuilder;import org.junit.test;import  com.mybatis.entities.person;public class testperson {@Testpublic  void testgetperson () {Inputstream is = getclass (). getClassLoader ()         . getResourceAsStream ("Conf.xml"); Sqlsessionfactory sessionfactory = new sqlsessionfactorybuilder ()          .build (IS); Sqlsession session = sessionfactory.opensession (); string statement =  "Com.mybatis.entities.PersonMapper.getPerson"; Person person = session.selectone (statement , 1); SYSTEM.OUT.PRINTLN (person);  // person [id=1, name=tom, age=23]}} 

Like Hibernate, we need a sessionfactory and a Session,

The creation of Sessionfactory requires a stream, which corresponds to the stream of the Conf.xml file.

The creation of the session is also very simple, opensession can be.


Tell MyBatis which SQL statement to invoke:

String statement = "Com.mybatis.entities.PersonMapper.getPerson";

The last side of the Getperson is just the ID value of our <select> tag configuration.


Because we need to pass a parameter ID to the SQL statement, we need to take a 1 on the second parameter.

Person person = session.selectone (statement, 1);

Represents a person object with a query ID of 1.


Final print, Query complete!


This article is from the "focus on Java,linux Technology" blog, please be sure to keep this source http://wuqinglong.blog.51cto.com/9087037/1723031

1. Getting Started with 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.