Chapter 1 Hibernate and MyBatis
Hibernate is the most popular O/R mapping framework at present. It was born in sf.net and has now become a part of Jboss. Mybatis is another excellent O/R mapping framework. Currently belongs to a subproject of apache.
MyBatis References Official Website: http://www.mybatis.org/core/zh/index.html
Hibernate reference materials: http://docs.jboss.org/hibernate/core/3.6/reference/zh-CN/html_single/
1.1 Introduction to Hibernate
Hibernate provides a relatively complete encapsulation of the database structure. Hibernate's O/R Mapping implements mapping between POJO and database tables, as well as automatic generation and execution of SQL. Programmers often only need to define the mapping relationship between POJO and database tables, and can complete persistence layer operations through the methods provided by Hibernate. Programmers do not even need to be proficient in SQL. Hibernate/OJB will automatically generate the corresponding SQL and call the JDBC interface to execute according to the established storage logic.
1.2 Introduction to MyBatis
The focus of iBATIS is on the mapping relationship between POJO and SQL. Then, by mapping the configuration file, the parameters required by SQL and the returned result fields are mapped to the specified POJO. Compared with Hibernate "O/R", iBATIS is an ORM implementation of "Sql Mapping".
Chapter 2 Development Comparison
Development speed
The real mastery of Hibernate is more difficult than Mybatis. Mybatis framework is relatively simple and easy to use, but it is also relatively simple. Personally, I think to use Mybatis well, you must first understand Hibernate.
Development Community
Hibernate and Mybatis are both popular persistence layer development frameworks, but the Hibernate development community is relatively lively, supports many tools, and updates are faster. The current highest version is 4.1.8. Mybatis is relatively calm and has fewer tools, and the current highest version is 3.2.
Development workload
Hibernate and MyBatis have corresponding code generation tools. Simple and basic DAO layer methods can be generated.
For advanced queries, Mybatis requires manual writing of SQL statements and ResultMap. Hibernate has a good mapping mechanism, so developers do not need to care about SQL generation and result mapping, and can focus more on business processes.
Chapter 3 System Tuning Comparison
Hibernate's tuning plan develops a reasonable caching strategy;
Try to use the lazy loading feature;
Adopt a reasonable Session management mechanism;
Use batch grabbing and set reasonable batch parameters (batch_size);
Carry out reasonable O/R mapping design
Mybatis Tuning Solution
MyBatis is consistent with Hibernate's Session life cycle in terms of Session, and a reasonable Session management mechanism is also required. MyBatis also has a Level 2 cache mechanism. MyBatis can perform detailed SQL optimization design.
SQL optimization aspects
Hibernate's query will query all fields in the table, which will cause performance consumption. Hibernate can also write SQL itself to specify the fields that need to be queried, but this destroys the simplicity of Hibernate development. Mybatis' SQL is written manually, so you can specify the fields for query as needed.
The tuning of Hibernate HQL statements requires printing of SQL, and many people dislike Hibernate's SQL because it is too ugly. MyBatis' SQL is written manually by yourself, so it is easy to adjust. But Hibernate has its own log statistics. Mybatis itself does not contain log statistics and uses Log4j for logging.
Scalability
The association between Hibernate and specific databases only needs to be configured in the XML file. All HQL statements have nothing to do with the specific database used, and are very portable. All SQL statements in the MyBatis project depend on the database used, so the support for different database types is not good.
Chapter 4 Object Management and Crawling Strategies
Object Management
Hibernate is a complete object/relational mapping solution that provides the functionality of object state management, so that developers no longer need to pay attention to the details of the underlying database system. That is, compared to the common JDBC/SQL persistence layer scenarios that require management of SQL statements, Hibernate adopts a more natural object-oriented perspective to persist data in Java applications.
In other words, developers using Hibernate should always pay attention to the state of the object and do not have to consider the execution of SQL statements. This part of the details has been managed by Hibernate and only developers need to understand when tuning the system performance.
MyBatis has no documentation in this area, so users need to manage the objects themselves in detail.
Crawl strategy
Hibernate has a good mechanism for crawling entity-associated objects. For each association relationship, it can be set in detail whether to delay loading, and four modes are provided: association crawling, query crawling, subquery crawling, and batch crawling. It is configured and processed in detail.
Mybatis' lazy loading is configured globally.
Chapter 5 Comparison of cache mechanisms
Hibernate cache
Hibernate level 1 cache is a Session cache. If you make good use of level 1 cache, you need to manage the life cycle of the Session well. It is recommended to use a Session in an Action operation. Level 1 cache requires strict management of Session.
Hibernate Level 2 cache is a SessionFactory-level cache. The cache of SessionFactory is divided into built-in cache and external cache. The built-in cache stores data contained in some collection attributes of the SessionFactory object (mapping element data and predetermined SQL statements, etc.), which is read-only for applications. The external cache stores a copy of the database data, which is similar to the primary cache. In addition to using memory as the storage medium, the secondary cache can also use external storage devices such as hard disks. The secondary cache is called process-level cache or SessionFactory-level cache. It can be shared by all sessions, and its life cycle exists and disappears with the life cycle of the SessionFactory.
MyBatis cache
MyBatis contains a very powerful query cache feature that can be configured and customized very easily. Many improvements to the cache implementation in MyBatis 3 have been implemented, making it more powerful and easy to configure.
By default, caching is not enabled. In addition to local session cache, it can enhance monetization and handle circular dependencies are also necessary. To enable Level 2 cache, you need to add a line to your SQL mapping file: <cache/>
That's it literally. The effect of this simple statement is as follows:
All select statements in the mapping statement file will be cached.
All insert, update and delete statements in the mapping statement file refresh the cache.
The cache will be retrieved using the Least Recently Used (LRU, the least recently used) algorithm.
Depending on the schedule (such as no Flush Interval, no refresh interval), the cache will not be refreshed in any chronological order.
The cache stores 1024 references to a list collection or object (regardless of what the query method returns).
The cache is considered to be a read/write (readable/writable) cache, meaning that object retrieval is not shared and can be safely modified by the caller without interfering with potential modifications made by other callers or threads.
All of these properties can be modified by cache elements' properties.
For example: <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
This more advanced configuration creates a FIFO cache and refreshes every 60 seconds, saving 512 references to the result object or list, and the returned object is considered read-only, so modifying them between callers in different threads will lead to conflicts. The available recovery strategies are, the default is LRU:
LRU least recently used: Remove objects that have not been used for the longest time.
FIFO First-in First-out: Remove objects in the order in which they enter the cache.
SOFT soft reference: Removes objects based on garbage collector state and soft reference rules.
WEAK Weak References: More aggressively remove objects based on garbage collector state and weak reference rules.
flushInterval can be set to any positive integer, and they represent a reasonable millisecond form of time period. The default is not set, that is, there is no refresh interval, and the cache is refreshed only when the statement is called.
size (number of references) can be set to any positive integer, remember the number of objects you cache and the number of available memory resources in your running environment. The default value is 1024.
The readOnly property can be set to true or false. A read-only cache returns the same instance of the cache object to all callers. Therefore, these objects cannot be modified. This provides important performance advantages. A readable and writeable cache returns a copy of the cache object (by serialization). This will be slower, but safe, so it is false by default.
Similarities
In addition to using the system's default caching mechanism, Hibernate and Mybatis' secondary caches can completely overwrite cache behavior by implementing your own cache or creating adapters for other third-party cache solutions.
Differences
Hibernate's secondary cache configuration is configured in detail in the configuration file generated by SessionFactory, and then it is configured in the specific table-object map.
MyBatis's secondary cache configuration is configured in detail in each specific table-object map, so that different cache mechanisms can be customized for different tables. And Mybatis can share the same cache configuration and instance in the namespace, which is implemented through Cache-ref.
Comparison of the two
Because Hibernate has a good management mechanism for query objects, users do not need to care about SQL. Therefore, if dirty data appears when using the secondary cache, the system will report an error and prompt.
In this regard, MyBatis requires special care when using L2 cache. If the scope of data update operations cannot be fully determined, avoid blind use of Cache. Otherwise, the appearance of dirty data will bring great hidden dangers to the normal operation of the system.
Chapter 6 Comparison and Summary of Hibernate and Mybatis
The similarities between the two
Hibernate and MyBatis can both generate SessionFactory from XML configuration file through SessionFactoryBuider, and then generate Session from SessionFactory, and finally execute transactions and SQL statements. Among them, the life cycles of SessionFactoryBuider, SessionFactory, and Session are almost the same.
Both Hibernate and MyBatis support JDBC and JTA transactions.
Mybatis Advantages
MyBatis can perform more detailed SQL optimizations and reduce query fields.
MyBatis is easy to master, while Hibernate has a higher threshold.
Hibernate Advantages
Hibernate's DAO layer development is simpler than MyBatis, which requires maintenance of SQL and result mapping.
Hibernate maintains and caches objects better than MyBatis, and it is more convenient to maintain objects that are added, deleted, modified and checked.
Hibernate database has good portability, MyBatis database has poor portability, and different databases need to write different SQL.
Hibernate has a better L2 cache mechanism, which can use third-party cache. MyBatis itself provides poor caching mechanisms.
Others summary
Hibernate has powerful functions, good database irrelevance, and strong O/R mapping capabilities. If you are quite proficient in Hibernate and properly encapsulate Hibernate, then the entire persistence layer code of your project will be quite simple, there is very little code to write, and the development speed is very fast and very cool.
The disadvantage of Hibernate is that the learning threshold is not low, and you must be proficient in it. You need to have strong experience and ability to design O/R mapping, how to balance the performance and object model, and how to use Hibernate well.
iBATIS is simple to get started with, learn and use, provides automatic object binding function for database queries, and continues with good SQL usage experience. It is quite perfect for projects that do not have such high object model requirements.
The disadvantage of iBATIS is that the framework is still relatively simple and the functions are still missing. Although the data binding code is simplified, the entire underlying database query actually has to be written by itself, the workload is relatively large, and it is not easy to adapt to rapid database modification.