MyBatis Environment Construction (i.)

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 the retrieval of the result set. MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plain old Java Objects, ordinary Java objects) to records in a database.

MyBatis's functional architecture is divided into three tiers:

(1) API Interface layer: provides interface APIs for external use, and developers manipulate the database through these local APIs. Once the interface layer receives the call request, it invokes the data processing layer to complete the specific data processing.

(2) Data processing layer: Responsible for the specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing and so on. Its primary purpose is to complete a database operation at the request of the call.

(3) Base support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and caching processing, these are common things, they are extracted as the most basic components.

Provides the most basic support for the data processing layer of the upper layer.

Second, the environment construction

1. Create a project

2. Create a database, table

CREATE TABLE`User' (' UserId 'int( One) not NULLauto_increment, ' LoginName 'varchar( -) not NULL, ' PassWord 'varchar( -) not NULLCOMMENT'Password', ' UserName 'varchar( A) not NULLCOMMENT'real name', ' creatdate 'datetime  not NULL,  PRIMARY KEY(' userId ')) ENGINE=InnoDB auto_increment=2015090005 DEFAULTCHARSET=UTF8;INSERT  into`User`VALUES('2015090004','Jalja','111111','Jalja','2015-09-05 21:46:59');

3. Defining entity classes (User.java)

 PackageCom.jalja.myBatis.model;Importjava.util.Date; Public classUser {Private intuserId; PrivateString LoginName; PrivateString PassWord; PrivateString UserName; PrivateDate creatdate;  Public intgetUserId () {returnuserId; }     Public voidSetuserid (intuserId) {         This. UserId =userId; }     PublicString Getloginname () {returnLoginName; }     Public voidsetloginname (String loginName) { This. LoginName =LoginName; }     PublicString GetPassword () {returnPassWord; }     Public voidSetPassword (String passWord) { This. PassWord =PassWord; }     PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }     PublicDate getcreatdate () {returncreatdate; }     Public voidsetcreatdate (Date creatdate) { This. creatdate =creatdate; }}
View Code

4. Add MyBatis configuration file Mybatis-data.xml and database configuration file jdbc.properties

Jdbc.properties

Jdbc.driverclassname=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://Localhost:3307/blog jdbc.username=Rootjdbc.password=111111

Mybatis-data.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> <!--reference jdbc.properties configuration file--<properties resource= "Com/jalja/mybatis/resource S/jdbc.properties "/> <environmentsdefault= "Development" > <environment id= "Development" > <transactionmanager type= "JDBC"/> <!--Configuring database connection Information-<datasource type= "Pooled" > <property name= "driv                 Er "value=" ${jdbc.driverclassname} "/> <property name=" url "value=" ${jdbc.url} "/> <property name= "username" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.pass Word} "/> </dataSource> </environment> </environments> </configuration>

5. Create a Com.jalja.myBatis.model.mapper package that is designed to hold the SQL mapping file and create a usermapper.xml file in the package, as shown in:

<?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 Map file name so that the namespace value is guaranteed to be unique, for example namespace= "Com.jalja.myBatis.model.mapper." Usermapper "is Com.jalja.myBatis.model.mapper (package name) +usermapper (usermapper.xml file removal suffix)--<mapper namespace= "Com.jalja.myBatis.model.mapper. Usermapper "> <!--To write the query's SQL statement in the Select tab, set the ID property of the Select tag to the Getuser,id property value must be unique and cannot reuse the ParameterType property to indicate the type of parameter used in the query, res The Ulttype property indicates the type of result set returned by the query Resulttype= "Me.gacl.domain.User"represents the object that encapsulates the query result into a user class returns the user class is the entity class corresponding to the Users table-<!--get a user object by ID query--<select id= "Finduserbyid" parametertype= "int" resulttype= "Com.jalja.myBa Tis.model.User ">Select* FROM user where userid=#{userid}</select> <!--creating users (Create)--<insert id= "AddUser" parametertype= "Com.jalja.myBatis.model.User" &G TINSERT INTO User (Loginname,password,username,creatdate) VALUES (#{loginname},#{password},#{username}, now ()) </insert> <!--Modify User (Update)--<update id= "UpdateUser" parametertype= "Com.jalja.myBatis.model.Use R ">Update user Set LoginName=#{loginname},password=#{password} where userid=#{userid}</update> <!--Remove User (remove)--<delete id= "DeleteUser" parametertype= "int" >Delete from user where UserId=#{userid}</delete> <!--query All users-<select id= "Finausersall" resulttype= "Com.jalja.myBatis.model.User" >Select*From user</select> </mapper>

6. register the Usermapper.xml file in the Mybatis-data.xml 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> <!--reference jdbc.properties configuration file--<properties resource= "Com/jalja/mybatis/resource S/jdbc.properties "/> <environmentsdefault= "Development" > <environment id= "Development" > <transactionmanager type= "JDBC"/> <!--Configuring database connection Information-<datasource type= "Pooled" > <property name= "driv                 Er "value=" ${jdbc.driverclassname} "/> <property name=" url "value=" ${jdbc.url} "/> <property name= "username" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.pass          Word} "/> </dataSource> </environment> </environments> <mappers> <!--registered Usermapper.xml file, Usermapper.xml is located under Com.jalja.myBatis.mapper this package,
So resource written com/jalja/mybatis/model/mapper/usermapper.xml--> <mapper resource= "com/jalja/mybatis/model/ Mapper/usermapper.xml "/> </mappers> </configuration>

7, the main function of creating Sqlsession sqlsession object is to complete the database access and result mapping, it is similar to the database session concept,

Because it is not thread-safe, the scope of the Sqlsession object needs to be restricted within the method. The default implementation class for Sqlsession is Defaultsqlsession,

It has two properties that must be configured: Configuration and Executor

 PackageCom.jalja.myBatis.util;Importjava.io.IOException;ImportJava.io.Reader;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder; Public classMybatisbaseutil { Public StaticSqlsession getsqlsession ()throwsioexception{String conf= "Com/jalja/mybatis/resources/mybatis-data.xml"; Reader Reader=resources.getresourceasreader (conf); //building a factory in sqlsessionSqlsessionfactory sessionfactory =NewSqlsessionfactorybuilder (). build (reader); //Create a sqlsession that can execute SQL in the mapping fileSqlsession sqlsession =sessionfactory.opensession (); returnsqlsession; }     Public Static voidclosesqlsession (sqlsession sqlsession) {if(sqlsession!=NULL) {sqlsession.close (); }    }     Public Static voidMain (string[] args)throwsIOException {System.out.println (getsqlsession ()); }}

8. Testing

 PublicList<user>Finausersall () {String SQL= "Com.jalja.myBatis.model.mapper." Usermapper.finausersall "; Sqlsession sqlsession=NULL; List<User> list=NULL; Try{sqlsession=mybatisbaseutil.getsqlsession (); List=sqlsession.selectlist (SQL); System.out.println ("Finausersall===>" +list.get (0). Getloginname ());//Jalja}Catch(IOException e) {e.printstacktrace (); }finally{mybatisbaseutil.closesqlsession (sqlsession); }        returnlist; }

MyBatis Environment Construction (i.)

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.