"Internet architecture" software architecture mybatis architecture (14)

osc_1q5l9zt9 2020-11-11 15:54:14
internet architecture software architecture mybatis


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]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云