编程知识 cdmana.com

"Internet architecture" software architecture mybatis architecture (14)

Today, let's talk about mybatis, I said before spring ioc,aop,mvc, The next step is to the persistence layer of the database . The order from top to bottom ,mvc,ioc, At the bottom is the persistence layer of the database .mybatis It is a framework widely used in the Internet and enterprises . Official reference document this document is very detailed :http://www.mybatis.org/mybatis-3/zh/index.html

『 Internet architecture 』 Software architecture -mybatis Architecture (14)

<!--more-->

Database access layer 4 Comparison of implementation schemes

JDBC

The earliest realization dao layer , It's all through jdbc The way

『 Internet architecture 』 Software architecture -mybatis Architecture (14)

  1. For a link , adopt DriverManager.getConnection
  2. structure sql sentence , Maybe this sql sentence , It is possible to add, delete, modify and check
  3. Set parameters , Follow jdbc The database is one-to-one
  4. perform sql, adopt execute
  5. Get the return result
  6. Build on results DO
  7. Close links

It's very complicated , It can be based on a component , Develop a tool class , Getting a link and closing a link are definitely two ways ,1-7 Steps can be built using proxy methods . The second step can be passed to the method in the form of parameters . Automatically help us get links , Set parameters , perform sql. It greatly simplifies our development of . Later, we began to develop and use jdbc template.

JdbcTemplate

『 Internet architecture 』 Software architecture -mybatis Architecture (14)

  1. structure sql sentence
  2. Build parameters
  3. call jdbc Template method
    3.1 For a link
    3.2 Set parameters
    3.3 perform sql
    3.4 Get the return result
    3.5 be based on result Object attribute mapping construction DO
    4 return DO object





although JdbcTemplate Simplify our database operations , But it has a problem ,sql Every sentence should be java class , The way the code is spliced sql, Finally, the code is very confusing , The type of database and java Mapping the types of . Write sql The sentence itself is a tedious thing ,ORM Object relation mapping , Two dimensions and java Inside bean, Do one-on-one configuration . There's no need to write sql Statement , And then it began to spread hibernate.

hibernate

hibernate It's a complete whole ORM frame , Contains basic queries , Insert , modify , Delete . adopt java api To make a call , It also includes the secondary cache, which is an additional , Natural support sql Anti injection .

『 Internet architecture 』 Software architecture -mybatis Architecture (14)

  1. obtain session
  2. Open transaction , return transaction object
  3. call save, Return execution result
    3.1 Configuration mapping
    3.2 expect DO Map generation SQL( The bottom is still jdbc, It's like we spring mvc The bottom layer is still used servlet)
    3.3 For a link
    3.4 Set up sql Parameters
    3.5 perform sql
    3.6 Release Links





  4. Commit transaction

hibernate Good as it is , But there are also drawbacks , The most inconvenient place , State control ( Free state , Persistent state , Transient data state ), Especially when the model is more complex, what is one-to-one , One to many , For one more , Many to many , It's easy to get dizzy , also HQL sentence , These sentences are hibernate Self generated , such DBA It's very depressing , We have a good grasp of performance research , It will feel heavier . And then a lot of people went from hibernate Into the JdbcTemplate ,JdbcTemplate Although it's more complicated , however sql The sentences are controllable .sql The writing method of the statement can test the experience of database .

mybatis

  • history

    Mybaits The predecessor was Apache An open source project of iBatis,2010 This project was initiated by apache software foundation Moved to google code And renamed it Mybatis,2013 year 11 Month to migrate to Github, at present mybaits By Github Maintenance of .

『 Internet architecture 』 Software architecture -mybatis Architecture (14)

  1. obtain session
  2. Open the transaction and return to Transaction
  3. call select
    3.1 Pull mapping configuration
    3.1.1 Build on configuration configstatement
    3.2 perform sql
    3.2.1 be based on configstatement Generate sql
    3.2.2 For a link
    3.2.3 Set up sql Parameters
    3.2.4 perform sql
    3.2.5 Release Links , return Do object , Return execution result







hiberate It's all generated by mapping itself sql sentence ,mybatis It's based on xml, What do you configure sql Just do what sql,sql Statements are controllable , It can be seen that . If something goes wrong, it can be executed by experience sql.

A comparison of the four

classification advantage shortcoming
jdbc Simple 、 pure 1、 You need to manually close the link 2、 The result set does not automatically reflect
jdbcTemplate Simple 、 pure 、 Automatic session management 、 The result is reflected in thanks 1、 Manual assembly SQL Management confusion
hirbernate High programming efficiency , No need to write sql. Low cost of database replacement 、 More perfect level 2 Cache 、 Automatic defense SQL Inject The threshold of complete mastery is high 、 Performance optimization is cumbersome 、 Complex thanks
myBatis The cost of learning is low 、 You can do it in more detail SQL Optimize , Reduce query fields 、 A unified SQL management The function is relatively simple 、 Maintenance needs to be written manually SQL、 After the table structure changes, it needs to be maintained manually SQL And Yingxie ( As many queries as possible , It's all written in business code , In this way, the distribution can be well completed )

mybatis The positioning of

myBatis Focus on sql In itself , It as a sql Thank you, not complete ORM, You need to write your own sql sentence , This is its advantage and disadvantage . Advantage is : Optimization is convenient , Make better use of sql Writing experience . The drawback is that it takes a long time to adjust the data after modification .

Try scenarios : Suitable for high performance requirements , There are a lot of queries and modifications , And business implementation does not have too much lazy data relational model , such as : Online retailers 、O2O Wait for the Internet Project .

The Internet Project on DAO Layer requirements :
1. Access to the database is updated purely
2. As far as possible, don't use the database for calculation
3.SQL Sentence can be targeted optimization ( Reduce query fields 、 Check the conditional sort example 、 The query condition hits the index as much as possible )


myBatis Architecture diagram

『 Internet architecture 』 Software architecture -mybatis Architecture (14)

myBatis Applied knowledge structure diagram

『 Internet architecture 』 Software architecture -mybatis Architecture (14)

  • Config

    Attribute configuration

<properties resource="app.properties">
<property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>

Three settings :
1. structure sessionFactory Time transfer ( priority : high )
2. be based on resource Attribute loading or url load ( priority : in )
3. be based on <propertite> Property settings ( priority : low )


Global parameter configuration

<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
 Specific reference :http://www.mybatis.org/mybatis-3/zh/configuration.html#settings

Environment configuration

&lt;environments default="development"&gt;
&lt;environment id="development"&gt;
&lt;transactionManager type="JDBC" /&gt;
&lt;dataSource type="POOLED" &gt;
&lt;property name="driver" value="${jdbc.driver}" /&gt;
&lt;property name="url" value="${jdbc.url}" /&gt;
&lt;property name="username" value="${jdbc.username}" /&gt;
&lt;property name="password" value="${jdbc.password}" /&gt;
&lt;/dataSource&gt;
&lt;/environment&gt;
&lt;/environments&gt;

data source :

unpooled Normal connection , A new connection is reestablished each time it is retrieved . Attributes are as follows :
• driver : Database driver class
• url: URL Address
• username: user name .
• password : Password to log in to the database .
pooled: Connection pool mode , All connections are taken from the connection pool , The connection pool is used to establish and recycle the connection , Except support unpooled The following attributes are supported in addition to the attributes :
• poolMaximumActiveConnections : Maximum number of activities , The default value is :10
• poolMaximumIdleConnections : Maximum number of free connections
• poolMaximumCheckoutTime : Get connection timeout wait maximum (checked out) Time , The default value is :20000 millisecond
• poolTimeToWait : Single access connection Maximum waiting time Default :20000 millisecond ( namely 20 second ).
• poolMaximumLocalBadConnectionTolerance Get connection retries Default :3
• poolPingQuery A test used to detect whether a connection is disconnected sentence
• poolPingEnabled Whether through execution poolPingQuery Sentence detection , The default value is :false.
• poolPingConnectionsNotUsedFor Connection detection interval , Default 60000.












typeAliases Alias configuration


&lt;typeAliases&gt;
&lt;typeAlias type="com.idig8.dao"/&gt;
&lt;typeAlias type="com.idig8.dao.UserInfo" alias="UserInfo"/&gt;
&lt;/typeAliases&gt;
* mappers  The file import 
> be based on  mapper  Import the specified resource file : resource| url |class
 be based on package  introduce : Scan the specified packet path for the current url

``` xml
<mappers>
<mapper resource="userInfo.xml" />
<package name="com.tuling.dao"/>
</mappers>

mapper Thanks for file configuration

mapper Common elements
• select – Mapping query language
• insert – Mapping insert statements
• update – Mapping update statements
• sql – A block of repeatable phrases that can be referenced by other statements .
• delete – Mapping delete statements
• resultMap Describes how to load objects from a database result set .
• cache – Cache configuration for a given namespace .
• cache-ref – References to other namespace cache configurations .







select Search tags


&lt;select id="selectUser" 
resultType="com.tuling.mybatis.test.UuserInfo"&gt; 
select * from user_info where id = #{id}
&lt;/select&gt;
 Its supporting properties are as follows :
&lt;select
id="selectUser" // statement id
parameterType="int" //  Parameter type 
resultType="hashmap"//  Return result category 
resultMap="personResultMap" //  Return the result and thank you 
flushCache="false" // 
useCache="true"
timeout="10000"
fetchSize="256"
statementType="PREPARED"&gt;
 Parameter reference method 
#{id, mode=in, jdbcType=INT, jdbcTypeName=MY_TYPE}

>insert update delete  label 

``` xml
<insert id="addUser"
parameterType="com.tuling.mybatis.test.UuserInfo">
INSERT INTO user_info (user_name,nick_name,password) VALUES
(#{userName},#{nickName},#{password})
</insert>

<update id="updateUser" 
parameterType="com.tuling.mybatis.test.UuserInfo" >
update user_info set user_name=#{userName} where id=#{id}
</update>

<delete id="deleteUser" parameterType="int">
DELETE from user_info where id=#{id}
</delete>

<sql> label

 Will repeat sql  Statement defines the text as a field 
<sql id="base_colume"> id,user_name,nick_name</sql>
 It can be done by  <include >  Introduce   Such as :
<include refid="base_colume"/>

resultMap


resultMap  yes myBatis  The appreciation of the object 

*    dynamic SQL To configure 
``` xml
<if>  label 
trim (where, set)  label 
foreach  label 

PS: Actually mybatis, I'm used to generating my own correspondence automatically xml, There are only simple additions and deletions in it , All business logic is not processed in tables, including associated queries , All in service Inside processing , then new new vo Just show it , This puts all the pressure on the program , The database is simpler .

版权声明
本文为[osc_1q5l9zt9]所创,转载请带上原文链接,感谢

Scroll to Top