The first layer of high salary Batis - open source analysis framework involves Java persistent source code analysis framework

Audio_J 2020-11-10 13:39:00
layer high salary batis open


Task a : Custom persistence layer framework

1.1 JDBC Review and problem analysis

JDBC Problem analysis :

problem Solution
1 Database configuration information is hard coded Use profile
2 Frequently create and release database connections Use connection pool
3 SQL sentence 、 Set parameters 、 There is a hard coding problem in obtaining the result parameters Use profile
4 Manually encapsulate the return result set , More complicated Using reflection 、 introspection

Be careful : Although there are two configuration files , But it's not recommended to put it in a file , Because one is often modified , One is almost constant , And it's not logical , It's just that you can do it in a special way without having to load each one manually xml file , Specific view 1.3.2 sqlMapConfig.xml Detailed explanation

1.2 Analysis of the framework of custom persistence layer

End of use :( project ) Introducing a custom persistence layer framework jar package
Provides two parts of configuration information : Database configuration information 、SQL Configuration information (SQL sentence 、 Parameter type 、 return type )

  1. sqlMapConfig.xml: Store database configuration information
  2. mapper.xml: Deposit sql Configuration information

Custom frame layer itself :( engineering ) The essence is right JDBC The code is encapsulated

  1. Load profile : According to the configuration file path , Load configuration file into byte input stream , Stored in memory
    establish Resource class , Method :InputStream getResourceAsStream(String path)
  2. Create two JavaBean( Container object ), What is stored is the content parsed out of the configuration file
    Configuration: Core configuration class , Deposit sqlMapConfig.xml What's coming out of it
    MapperStatement: Mapping configuration class , Deposit mapper.xml What's coming out of it
  3. Parse configuration file :dom4j
    Create a class :SqlSessionFactoryBuilder Contains methods build(InputStream in) There are two main things to do :
    3.1 Use dom4j Parse configuration file , Encapsulate the parsed content into the container object
    3.2 establish sqlSessionFactory object , production SqlSession, The conversation object ( Add, delete, modify and search are encapsulated here ), Factory mode is used here , Reduce the coupling between programs ( Not directly new One SqlSession)
  4. establish SqlSessionFactory Interface and implementation class DefaultSqlSessionFactory, Method openSession() To produce sqlSession
  5. establish SqlSession Interface and implementation class DefaultSession, Define the database CRUD operation (selectList、selectOne、update……)
  6. establish Executor Interface and implementation class SimpleExecutor Implementation class ,query(Configuration,MapperStatement,MapperStatement,Object... params) Method , What we're doing is JDBC Code

1.3 IPersistence_Test To write

IPersistence_Test You can think of it as the user side , First complete the user side writing , Relatively simple , All you have to do is write the configuration file and introduce jar package

Two types of configuration files :

sqlMapConfig.xml : Write configuration information about database connection
XXXMapper.xml : ( such as UserMapper.xml) Write specific modules ( For example, user module ) The sentence information of

1.3.1 XXXMapper.xml Detailed explanation

XXXMapper.xml The main functions of the system are as follows :

  1. Configuration really needs to be in MySql What's going on inside sql sentence
  2. Realize the positioning of specific statements , That is to say, we need to give sql A specific sign , namely statementId
  3. Specifies the encapsulation type of the returned result
  4. Specifies the type of parameter passed in

But writing like this only works user surface , Suppose we have product surface , So use selectList You can't determine which statement is used , So add a namespace namespace

<mapper namespace="user">
<!--sql Unique identification of :namespace.id To form a ,statementId-->
<!-- In order to be able to locate specific select sentence , I'm going to give one id-->
<!--resultType Represents the entity you want to encapsulate , Therefore, it is necessary to obtain the corresponding entity and attribute from the corresponding path through reflection -->
<select id="selectList" resultType="com.jlgl.pojo.User">
select * from user
</select>
<!-- This article sql When a statement is executed, it needs parameters -->
<!-- Multiple parameters pass , Have an object-oriented idea , Encapsulating multiple objects into an entity -->
<!--
User user=new User();
user.setId();
user.setUsername();
-->
<!-- Therefore, the parameters also need to obtain the corresponding entities and attributes through reflection -->
<!-- In order to assign the corresponding attribute to the corresponding placeholder , Will the ? Change to a custom placeholder -->
<select id="selectOne" resultType="com.jlgl.pojo.User" paramterType="com.jlgl.pojo.User">
select * from user where id =#{id} and username = #{username}
</select>
</mapper>

1.3.2 sqlMapConfig.xml Detailed explanation

in order to Resource load xml The file is loaded only once , We need to mapper.xml And put it in , need mapper.xml The full path of

<configuration>
<!-- Database configuration information -->
<dataSource>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://120.48.8.213:3306/audio_2020"></property>
<property name="username" value="root"></property>
<property name="password" value="root1028*1"></property>
</dataSource>
<!-- in order to Resource load xml The file is loaded only once , We need to mapper.xml And put it in , need mapper.xml The full path of -->
<mapper resource="UserMapper.xml"></mapper>
</configuration>

1.4 Resources Class definition

The essence of the custom persistence layer framework is to utilize dom4j technology , Written for the user side xml Document analysis , Then encapsulate it into the configuration class , Finally, the configuration class is passed layer by layer to Executor Of query Method execution JDBC Code

Resources Class defines a method , The purpose is to load the configuration file into a byte input stream , Stored in memory

1.5 Container object definition

Container object :MapperStatement and Configuration, These two container objects store the contents parsed from the configuration file

MapperStatement From xxxMapper Read the contents inside , therefore xxxMapper The properties of the need to be stored in MapperStatement The corresponding class attribute

Configuration The function is to store, that is sqlMapConfig The content of , In fact, it is the database configuration information

1.6 Parse the core configuration file sqlMapConfig

As mentioned earlier , Parsing the core configuration file takes two steps :

3. Parse configuration file :dom4j
Create a class :SqlSessionFactoryBuilder Contains methods build(InputStream in) There are two main things to do :
3.1 Use dom4j Parse configuration file , Encapsulate the parsed content into the container object
3.2 establish sqlSessionFactory object , production SqlSession, The conversation object ( Add, delete, modify and search are encapsulated here ), Factory mode is used here , Reduce the coupling between programs ( Not directly new One SqlSession)

The first is to use dom4j Parse configuration file , Specifically, use XMLConfigBuilder.parseConfig(InputStream in) Realized
take sqlMapConfig.xml Generate Configuration

1.7 Resolve the mapping configuration file mapper.xml

stay XMLConfigBuilder Inside , call XMLMapperBuilder Of parse Method , Read XXXMapper.xml Generate MapperStatement, And put it in Configuration Of mapperStatementMap Inside

1.8 Conversation object sqlSession Class definition

In the reply object , Use Configuration The converted configuration file information stored in it , Complete the connection with the database and data acquisition operation

1.9 Conversation object sqlSession Method definition

With selectList() For example , Three steps need to be taken :

1 initialization Executor object
2 obtain Comfiguration What's in it xxxMapper.xml Converted MapperStatement
3 perform Executor Of query Method

1.10 Query object query Method definition

Six steps are required :

1 Registration drive , Get the connection
2 obtain sql sentence , And then switch sql sentence , At this point, we need to configure the tag parser to parse and process the placeholder ( It's directly used here Mybatis Code for )
3 Get preprocessing object :preparedStatement
4 Set parameters
5 perform sql
6 Encapsulate the return result set

Be careful :
stay mapper.xml When the configuration , Not directly written as ? The reason is that , In order to obtain the corresponding properties of the incoming object directly according to the property name
Object-oriented thinking , Encapsulate parameters as objects , Back again , Specific view buildParameterMapping, Not will String Type of content Put it directly in List, It's transformed into ParameterMapping Objects in the List

1.11 Parameter setting realizes

Using reflection , According to the parameter name , Get the attribute value of entity object , Then get the specific parameter value in the object

1.12 Encapsulate the return result set to implement

Use reflection or introspection , According to the corresponding relationship between database table and entity , Finish packaging

1.13 Client End run test

How to use IPErsistence frame :
First of all, will IPersistence Class packing , And then in IPersistence_test Of pom Just introduce the package

UML Class diagram ( important , It needs to be understood ):

1.14 Function extension ——getMapper Method realization

There are some problems with the custom persistence layer framework :

1 Duplicate code .Dao Layer load configuration file 、 obtain SqlSessionFactory、 production sqlSession Object has code duplication
2 Hard coding problem . The hard coded statementId

Solutions :

 Don't Dao Implementation class of , Use proxy pattern to implement Dao The proxy implementation class of layer interface

Specific steps :

1 stay SqlSession establish getMappper, And in DefaultSession rewrite
3 stay Client End direct call

1.15 Function extension —— A dynamic proxy invoke Method realization

Be careful : No matter how concise 、 Optimize , Finally, it's time to implement the underlying methods

xxxMapper.xml The specification of the document should be complied with ,namespace It should be consistent with the fully qualified name of the interface , The method name should be consistent with the interface method name

reason :

invoke There is no way to get statementId Of ( The way we used is hard coded ), However, the name can be fully qualified through the interface . The method name is namespace.id, It's assembled statementId
版权声明
本文为[Audio_J]所创,转载请带上原文链接,感谢

  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课程百度云