"Todo" MyBatis learning-Partial theory

Source: Internet
Author: User

I have written several mybatis related articles before:

Http://www.cnblogs.com/charlesblc/p/5906431.html "SSM (springmvc+spring+mybatis) framework program on Idea"

And this one:

Http://www.cnblogs.com/charlesblc/p/5939505.html "Add MyBatis on top of a Java Spring MVC project"

And this article deals with MyBatis content separately:

http://www.cnblogs.com/charlesblc/p/5973071.html "mybatis Study-partial practice (individual MyBatis Project)"

This article is mainly to summarize the content of learning mybatis biased theory.

Now the main reference is the following two:

Http://www.yihaomen.com/article/java/302.htm

http://limingnihao.iteye.com/blog/781671

Maybe there's this: http://www.cnblogs.com/xdp-gacl/p/4261895.html

The first is http://www.yihaomen.com/article/java/302.htm, which is a series.

Performance is better than hibernate. and also relatively lightweight.

What is 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 (Plan old Java Objects, plain Java objects) to records in a database.

The basic idea of ORM tools
Whether it's used hibernate,mybatis or not, you can have one thing in common:
1. Get sessionfactory from the configuration file (usually in the XML configuration file).
2. Session generated by Sessionfactory
3. In the session to complete the deletion of data and other changes and transaction submissions.
4. Close the session after use is complete.
5. There is a mapping configuration file between the Java object and the database, usually an XML file.

Below are the explanations for these configuration files:
1.configuration.xml is mybatis used to build sessionfactory, which mainly contains the database connection related things, as well as the Java class corresponding aliases, such as <typealias alias= "User" type = "Com.yihaomen.mybatis.model.User"/> This alias is very important, you in the specific class mapping, such as User.xml Resulttype is corresponding here. To be consistent, of course, there is a separate definition of the resulttype here, and then the other way around.

<?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>    <typealiases>         <Typealiasalias= "User"type= "Com.yihaomen.mybatis.model.User"/>     </typealiases>     <Environmentsdefault= "Development">        <EnvironmentID= "Development">        <TransactionManagertype= "JDBC"/>            <DataSourcetype= "Pooled">            < Propertyname= "Driver"value= "Com.mysql.jdbc.Driver"/>            < Propertyname= "url"value= "Jdbc:mysql://127.0.0.1:3306/mybatis" />            < Propertyname= "username"value= "root"/>            < Propertyname= "Password"value= "Password"/>            </DataSource>        </Environment>    </Environments>        <mappers>        <MapperResource= "Com/yihaomen/mybatis/model/user.xml"/>    </mappers></Configuration>
View Code

2. Configuration.xml inside the <mapper resource= "Com/yihaomen/mybatis/model/user.xml"/> is the XML configuration file that contains the class to be mapped.

In the User.xml file, the main definition is the various SQL statements, and the parameters of these statements, as well as the types to be returned.

<?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.yihaomen.mybatis.models.UserMapper">    <SelectID= "Selectuserbyid"ParameterType= "int"Resulttype= "User">select * from ' user ' where id = #{id}</Select></Mapper>
View Code

3. Create the Java class corresponding to the database and the mapping file.
Build the Package:com.yihaomen.mybatis.model under Src_user and create the User class under this package:

 PackageCom.yihaomen.mybatis.model; Public classUser {Private intID; PrivateString UserName; PrivateString Userage; PrivateString useraddress;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }     PublicString getuserage () {returnUserage; }     Public voidsetuserage (String userage) { This. Userage =Userage; }     PublicString getuseraddress () {returnuseraddress; }     Public voidsetuseraddress (String useraddress) { This. useraddress =useraddress; }}
View Code

Add the SQL that was built for the table:

Create TABLE`User' (' ID 'int( One) not NULLauto_increment, ' UserName 'varchar( -)DEFAULT NULL, ' Userage 'int( One)DEFAULT NULL, ' useraddress 'varchar( $)DEFAULT NULL,  PRIMARY KEY(' id ')) ENGINE=InnoDB auto_increment=2 DEFAULTCHARSET=UTF8;Insert  into`User`VALUES('1','Summer',' -','Shanghai,pudong');
View Code

Here is the main program. Build Com.yihaomen.test the package under the TEST_SRC source directory and set up test class tests:

 Packagecom.yihaomen.test;ImportJava.io.Reader;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder;ImportCom.yihaomen.mybatis.model.User; Public classTest {Private Staticsqlsessionfactory sqlsessionfactory; Private StaticReader Reader; Static{        Try{Reader= Resources.getresourceasreader ("Configuration.xml"); Sqlsessionfactory=NewSqlsessionfactorybuilder (). build (reader); }Catch(Exception e) {e.printstacktrace (); }    }     Public Staticsqlsessionfactory getsession () {returnsqlsessionfactory; }         Public Static voidMain (string[] args) {sqlsession session=sqlsessionfactory.opensession (); Try{User User= (User) session.selectone ("Com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1);        System.out.println (User.getuseraddress ());        System.out.println (User.getusername ()); } finally{session.close (); }    }}
View Code

In the second chapter, we will talk about the operation mode based on the interface, add and delete and change.
The entire project directory structure is as follows:

MyBatis Practical Course (MyBatis in action): Programming in the form of an interface

A simple query was implemented earlier. Note that this is done using the sqlsession instance to directly execute the mapped SQL statement sentence:

Session.selectone ("Com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1)

There are simpler ways to do it, and it's a better approach: use interfaces that properly describe parameters and return values from SQL statements (such as Iuseroperation.class).

"Todo" MyBatis learning-Partial theory

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.