MyBatis (Ibatis) Understanding

Source: Internet
Author: User

Mybatis
MyBatis is an excellent persistence layer box that supports ordinary SQL queries, stored procedures, and advanced mappings
Rack MyBatis eliminates the manual setting of almost all JDBC code and parameters, as well as the knot
The retrieval of the fruit set. MyBatis using simple XML or annotations for configuration and raw mapping
, the pojos of the interface and Java (Plan old Java Objects, normal Java
Image) is mapped to a record in the database.

MyBatis Core

Steps to use:
1. Import Jar Package
2, create a new mybatis configuration file, file type is XML, name casually. Plus the file's DTD to verify the file header,
<?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" >
The root node is a configuration, configuring the environment environments, one for the development environment one for the online environment. The environment needs to configure the data source, transaction manager and other information
<environments default= "Development" >
<environment id= "Development" >
<transactionmanager type= "JDBC" ></transactionManager>
<datasource type= "Pooled" >
<property name= "Driver" value= "Com.mysql.jdbc.Driver"/>
<property name= "url" value= "Jdbc:mysql:///mydb"/>
<property name= "username" value= "root"/>
<property name= "Password" value= "root"/>
</dataSource>
</environment>
</environments>
The configuration file is basically complete, then the main configuration file is read in the main method, and the Sqlsessionfactory object is created.
Reading configuration Files
Reader reader = resources.getresourceasreader ("config + +");
Create a Sqlsessionfactory object
Sqlsessionfactory factory = new Sqlsessionfactorybuilder (). build (reader);
With the Sqlsessionfactory object, you can create a Session object
sqlsession session = Factory.opensession ();
Session.close ();
Perform the action that is expected between the start and end of the transaction. and commit the transaction before closing the transaction
Session.commit ();
If you do not want to write this code to manually commit the transaction, you can add a Boolean parameter to the session again, indicating that the transaction is committed automatically.
Create a package named DAO or mapper in your project, and then create a usermapper.xml configuration file in the package that introduces the DTD document header,
<?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" >
The root node is mapper, the node has the namespace attribute, the value of the property is written as a fully qualified name that prefers a DAO class, preferably with a connection to the current profile name, such as a configuration name of Usermapper.xml, You can define its Namespace property value as the current package name plus Userdao, which is the fully qualified name of the class name. The root node can directly write the usual use of SQL statements, according to the difference in the change of injury. The corresponding four nodes are insert/delete/update/select respectively.
<select id= "FindByID" parametertype= "int" resulttype= "User" >
Select Id,username,password from t_user where id = #{id}
</select>
For example, the above query, the id attribute corresponds to the first name of the method in the DAO class, the type of the parameter passed in when the parametertype corresponds to the query, the result of resulttype corresponding query result and type can also be the return value type, the query statement's restriction condition uses #{} The way to enclose the attribute field of the constraint.
This can be used when used in the Main method:
User user = Session.selectone ("Com.kaishengit.dao.UserDao.findById", 45);
The SelectOne representative queries only two parameters in a method, the first parameter is the name of the method to be executed, the name is written in a fully named way, the ID method in the Mapper configuration file is accurate, and the second parameter is the value in the constraint condition of the query. The results that are queried are automatically encapsulated into the user object.
Add a mapping file such as Usermapper to the master configuration file of MyBatis before you actually query it
<mappers>
<mapper resource= "Com/kaishengit/mybatis/mapper/usermapper.xml"/>
</mappers>
The disadvantage of querying in this way is to write a string that is similar to the fully qualified name of the method at the time of the query, so when actually used, you can create an interface with the same value as the Namespace property in the mapping file, defining the methods of these query operations defined in the mapping file in the interface. Creating a Userdao interface in a DAO or mapper package defines some class methods that are written in the configuration file in the interface, the name of the method and the ID number that is the same as the name of the value, and the parameter type is the same as the type in the mapping file. The return value type determines, depending on the situation, that when querying an object, an object can be used to receive, and when the query is a collection, the result set type in the configuration file is still the user class, but the type in the method in the interface is a collection.
Save operation:
After saving can be like hibernate after saving the object's primary key value, in the mapping file, the Save node added attributes, Usergeneratedkeys property value is True, indicating the use of the auto-growth type of the primary key value. The Keyproperty value is the ID representing the id attribute value of the user object. KeyColumn is used to define column names.
You can write an alias in the master configuration file if you still want to write the method based on the fully qualified name at the return result type.
<typeAliases>
<typealias type= "Com.kaishengit.poo.User" alias= "User"/>
</typeAliases>
If you write this way, you do not have to write the fully qualified name of the result type in the mapping file as long as the package name. But if you write like this, you don't have to add a Pojo class, you have to fill in an alias, you can write it when you actually use it.
<package name= "Com.kaishengit.pojo"/>
All entity classes in the entire Pojo package are included in alias management. Aliases are class names
Perform a delete operation
When the queried property name is not a field in the table, for example, the field name in the table is Stuname, and the property name of the entity class is username, then you can avoid this problem in the form of an alias in the SQL statement
Select Stuname as username from
The second solution is to use SELECT * from to query
The return value type is no longer used with the Resulttype type, but instead uses the Resultmap property, the property value can be defined as UserMap, a Resultmap node is created in the mapping file, and the Type property value remains the User,id attribute value defined previously.
<resultmap type= "User" id= "UserMap" >
<id property= "id" column= "id"/>
<result column= "Stuname" property= "username"/>
<result column= "password" property= "password"/>
</resultMap>
The Column property value is the field name in the database of the query's result set, and the property is the attribute name in the Pojo entity class.

Inquire:
When there are multiple parameters at the time of the query
The first type:
Encapsulates the parameters into a map, encapsulating the query criteria into a map
The second type:
Encapsulates a parameter as an object of a Pojo class such as a user object
The third type:
is passed directly as a parameter, and the parameter type is not written in the mapping file. Instead of using the form of #{param1} in a query statement to define the parameters to pass in, the type is not written, as long as the type and number of incoming parameters are consistent with the number and type of the SQL statement.

Query all
When the query is all the result is a list collection, but the Resulttype attribute value in the mapping file is still user.

Multiple table query:
Use a connection query statement
because it is not possible to use Resulttype to represent a result type, use Resultmap to represent the mapping of the result set.
<select id= "findbyidwithnews" parametertype= "int" resultmap= "Findalluser";
Select T_user.id,username, Password,t_news.id as Newsid,title from
T_user
left JOIN t_news on t_user.id = T_news.uid
WHERE t_user.id = #{id }
</select>
<resultmap type= "User" id= "Findalluser";
<id property= "id" column= "id"/>
<result property= "username" column= "username"/>
<result property= "password" column= "password"/>
<collection property= "newslist" oftype= "News";
<id property= "id" column= "newsid"/>
< Result property= "title" column= "title"/>
</collection>
</resultMap>

User and news is a one-to-many relationship, so using collection to encapsulate the property attribute value is the name of the collection property in the User entity class attribute, OfType is used to describe the type of value stored in this collection is the news type,
When it is a many-to-one relationship, the use of the same method and a pair of the same, because many-to-one query is not a collection, but I an object, so use the association node, and no longer with the OfType property, but with the Javatype property.
<select id= "findAll" resulttype= "list" resultmap= "Findnews";
Select T_news.id,title,uid,username, PASSWORD from T_news
left JOIN t_user on t_news.uid = T_user.id
</select>
<resultmap type= "News" id= " Findnews,
<id property= "id" column= "id"/>
<result property= "title" column= "title"/>
< Association property= "User" column= "UID" javatype= "user",
<id column= "UID" property= "id"/>
< Result property= "username" column= "username"/>
<result property= "password" column= "password"/>
< /association>
</resultMap>

Another query:
now finds the Address object based on Addrssid, obtains the UserID, obtains the user object according to the UserID, the Select property in the association node in Resultmap, The query indicating this result is queried by another select. column is used to define which field value in the first query condition executes the second SELECT statement and pass in the

as a constraint to the second SELECT statement.

Example:
<!--another way to query, two-time single-table query stitching--
<select id= "Findaddressbyid" parametertype= "int" resultmap= "Addressmap" >
SELECT * FROM address where id = #{id}
</select>

<select id= "Finduserbyid" parametertype= "int" resultmap= "UserMap" >
SELECT * from user where id = #{id}
</select>

<resultmap type= "Address" id= "Addressmap" >
<id column= "id" property= "id"/>
<result column= "Address" property= "Address"/>
<association property= "user" javatype= "user" select= "Finduserbyid" column= "user_id"/>
</resultMap>

<resultmap type= "User" id= "UserMap" >
<id column= "id" property= "id"/>
<result column= "username" property= "username"/>
<result column= "password" property= "password"/>
</resultMap>

Dynamic SQL
Sometimes we need to use dynamic SQL when the conditions of the query are uncertain. For example, we sometimes have to query the user object based on the username, and sometimes we may need to query the user object based on the username and password.
Therefore, you need to use dynamic SQL to query. The query condition is encapsulated into a map collection or a user object for querying when it is actually used.
If
<select id= "Findbywhere" resulttype= "User" >
SELECT * FROM user
<where>
<if test= "Username! = NULL" >
Username = #{username}
</if>
<if test= "Password! = null" >
and password = #{password}
</if>
</where>
</select>
Choose
<select id= "Findbychoose" parametertype= "map" resulttype= "User" >
SELECT * FROM user
<where>
<choose>
<when test= "Username! = NULL" >
Username = #{username}
</when>
<when test= "Password! = null" >
Password = #{password}
</when>
<otherwise>
</otherwise>
</choose>
</where>
</select>
where
<select id= "Findbywhere" resulttype= "User" >
SELECT * FROM user
<where>
<if test= "Username! = NULL" >
Username = #{username}
</if>
<if test= "Password! = null" >
and password = #{password}
</if>
</where>
</select>
Update
<update id= "UpdateInfo" parametertype= "User" >
Update user
<trim prefix= "Set" suffixoverrides= "," prefixoverrides= "," >
<if test= "Username! = NULL" >
, username = #{username}
</if>
<if test= "Password! = null" >
, Password = #{password}
</if>
</trim>
WHERE id = #{id}
</update>
Foreach:
<select id= "Findbyforeach" parametertype= "list" resulttype= "User" >
SELECT * FROM user
where ID in
<foreach collection= "list" index= "index" item= "Item" open= "(" close= ")" separator= "," >
#{item}
</foreach>
</select>


Cache

<mapper namespace= "Com.kaishengit.mapper.NewsMapper" >
<cache/>
...
</mapper>
The efficacy is as follows:
• All SELECT statements in the mapping statement file will be cached
• All INSERT, UPDATE, DELETE statements in the map statement file flush the cache
• The cache uses least recentily used (LRU, a seldom-used) algorithm to retract
• Refreshes the cache based on time intervals and does not refresh by default
• The cache stores 1024 references to a list collection or object
• Cache is considered a read/write cache
Change Cache
<cache eviction= "FIFO" flushinterval= "60000" size= "512"
Readonly= "true"/>
It is configured with a FIFO cache that refreshes the cache every 60 seconds, stores 512 references to the object or collection, and caches the cache as read-only.

Eviction Recovery Strategy
LRU: Least recently used, remove objects that have not been used for a long time (default)
FIFO: FIFO: Remove them by the order in which they are entered in the cache
soft: Soft Reference: Removing objects based on garbage collector state and soft reference rules
Weak: Weak references: More aggressively remove objects based on the garbage collector state and weak reference rules.
flushinterval (Refresh interval): Can be set to any positive integer
size (number of references) can be set to any positive integer, to remember the number of objects you cache and you run
The number of available memory resources for the environment. The default value is 1024.
The readonly (read-only) property can be set to TRUE or false. Read-only caching is reusing to all callers
Back to the same instance of the cached object. Therefore, these objects cannot be modified. This provides a very important performance advantage.
A read-write cache reusing back a copy of the cached object (by serialization). This will be slower, but safe, so
The default is False.


MyBatis and Spring Integration:

1. Import Myatis-spring.jar
2. New spring configuration file Applicationcontext.xml, configure transaction manager, database connection pool, configure MyBatis sqlsessionfactory, configure automatic Scan mapper Bean
<!--transaction Manager--
<bean id= "TransactionManager"
Class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager"
>
<property name= "DataSource" ref= "DataSource"/>
</bean>
<!--DBCP Data Source-
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >
<property name= "Driverclassname"
Value= "Com.mysql.jdbc.Driver" ></property>
<property name= "url" value= "Jdbc:mysql:///mydb" ></property>
<property name= "username" value= "root" ></property>
<property name= "Password" value= "root" ></property>
<property name= "InitialSize" value= "5" ></property>
<property name= "maxactive" value= "></property>"
</bean>
<bean id= "Sessionfactory"
class= "Org.mybatis.spring.SqlSessionFactoryBean" >
<property name= "DataSource" ref= "DataSource" ></property>
<property name= "Typealiasespackage"
Value= "Com.kaishengit.entity" ></property>
</bean>
<!--auto-scan Mapper--
<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name= "basepackage" value = "Com.kaishengit.dao"/>
</bean>
Configuring the spring Listener in Web. xml
<listener>
<listener-class>org.springframework.web.context.contextloaderlistener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>

MyBatis (Ibatis) Understanding

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.