MyBatis Development Notes Quick Start _java

Source: Internet
Author: User

Rapid popularization

1. 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 encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java Pojo (Plain old Java Objects, normal Java objects) to records in the database.
MyBatis implements interface binding and is more convenient to use.

Improved object-relational mapping for higher efficiency

MyBatis uses powerful, OGNL-based expressions to eliminate other elements.

2. Functional framework

3, the implementation process

Principle Detailed:

The MyBatis application is created from an XML configuration file sqlsessionfactory,sqlsessionfactory based on configuration, the configuration is from two places, one is the configuration file, the other is the annotation of Java code, get a sqlsession. Sqlsession contains all the methods needed to execute SQL, you can run the mapped SQL statement directly through the sqlsession instance, complete the data deletion, modification and transaction submission, and then close the sqlsession after use.

This article introduces the key mybatis simple annotation

key annotation Words:

@Insert: Inserting SQL is exactly the same as XML insert SQL syntax

@Select: Querying SQL is exactly the same as the XML Select SQL syntax

@Update: Update SQL exactly as XML update SQL syntax

@Delete: Deleting SQL is exactly the same as XML delete SQL syntax

@Param: Incoming parameters

@Results: Result Collection

@Result: Results

1. Domain Model:

public class Userdo {
private Long ID;
Private String userName;
Private Date gmtcreate;
Private Date gmtmodified;
Public Long GetId () {return
ID;
}
public void SetId (Long id) {
this.id = ID;
}
Public String GetUserName () {return
userName;
}
public void Setusername (String userName) {
this.username = userName;
}
Public Date Getgmtcreate () {return
gmtcreate;
}
public void Setgmtcreate (Date gmtcreate) {
this.gmtcreate = gmtcreate;
}
Public Date getgmtmodified () {return
gmtmodified;
}
public void setgmtmodified (Date gmtmodified) {
this.gmtmodified = gmtmodified;
}
}

2. Interface Definition:

Public interface Userdao {
@Insert (Insert into T_user (gmt_create, gmt_modified, user_name) VALUES (now (), now (), #{  UserName}) ") Public
int Insert (@Param (" UserName ") String userName);
@Select (' select * from t_user WHERE id = #{id} ') public
Userdo Selectbyuserid (@Param ("id") Long ID);
@Update ("Update t_user SET gmt_modified = Now (), user_name = #{username} WHERE id = #{id}") Public
int Udpatebyid (@Par AM ("UserName") String UserName, @Param ("id") Long ID);
@Delete (' Delete from t_user WHERE id = #{id} ') public
int Udpatebyid (@Param ("id") Long ID);
}

3. mybatis XML config:

<!--mybatis annotation-->
<bean id= "sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" >
<property name= "DataSource" ref= "Mysqlbase"/> <!--only need to configure your own data sources-->
</bean> 
< Bean id= "Userdao" class= "Org.mybatis.spring.mapper.MapperFactoryBean" >
<property name= "Mapperinterface" Value= "Com.yuanmeng.userDAO"/> <!--MyBatis interface--> <property name= "Sqlsessionfactory"
Sqlsessionfactory "/> <!--sqlsession factory-->
</bean>

In this way, we completed the MyBatis use annotation demo, is not feel very simple ~ ~

If you are familiar with MyBatis XML, in most cases, we need to map the field names of the database tables with class do. MyBatis annotations also provide a mapping function, with a similar syntax.

@Select ("Select * from tsp_template WHERE id = #{id}")
@Results (value = {@Result (property = ' userName ', column = ' Use R_name ", Javatype = string.class, Jdbctype = Jdbctype.varchar)}) public 
Userdo Selectbyid (@Param (" id ") Long ID);

Of course, the above is just no longer simple SQL. Consider if we have this requirement, update the user information, and hope to update the specified attribute value, in other words, dynamically generate SQL like XML. Then we can't simply use @update annotations. Fortunately, the powerful MyBatis also provides dynamic SQL assembly.

Dynamic SQL

The corresponding relationship is as follows

@Insert: @InsertProvider
@Select: @SelectProvider
@Update: @UpdateProvider
@Delete: @DeleteProvider

The four provider annotation identities use dynamic SQL, using the syntax format:

@UpdateProvider (type = Userprovider.class, method = "Updatesql")

How to construct dynamic SQL

public class Userprovider {
/**
* udpate
* @param userdo userdo
* @return
/Public String Updatesql (Final Userdo Userdo) {return
new SQL () {
{
UPDATE ("T_user");
SET ("gmt_modified = Now ()");
if (userdo.getusername ()!= null) {
SET ("user_name = #{username}");
WHERE ("id = #{id}}");
}
. ToString ();
}
}

This article refers to a comparison of the basis of knowledge, such as the need for in-depth understanding of the official website documents or look at the source code.

Summarize:

1. How do you choose XML and annotations? Each person, each of the code have their own habits, XML, annotations have advantages and disadvantages, XML disadvantage: When the model attribute changes, need to change from do to DAO to XML, think about the egg pain ~ XML also has advantages, SQL fragment multiplexing convenient, syntax approachable, unlike annotations, construct a dynamic statement, You also have to build a class, and when a section of SQL is referenced by several, the code appears redundant, then you have to use XML to extract common usage. Spit the next mybatis annotation, that annotation is not useless. No, MyBatis is suitable for the scene that the model attribute changes frequently, because can combine the reflection, the regular match constructs the SQL (pure blind slanting, the individual idea, should be possible to realize, another day). It can be said that the MyBatis annotation has a good advantage to make up for the XML disadvantage. The two complement each other ~

The above is a small set to introduce the MyBatis development annotation Quick Start, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.