Comparison of Persistence Layer Framework Hibernate and MyBatis

Reprinted from: https://zhuanlan.zhihu.com/p/29242045



Recently, I have seen many people questioning on the Internet.... Now many Web projects use MyBatis, I don't feel that MyBatis is any better. From the perspective of development efficiency, whether it is Hibernate's reverse engineering or automatic table building, association mapping is better than MyBatis is much more convenient. Is it just because of the speed, Hibernate also has a cache. Or, the two are suitable for different occasions. Or, MyBatis appears later than Hibernate, is it better? So I recently made a comparison summary between Hibernate and MyBatis. I hope everyone can point out the wrong things...

Hibernate is a very popular O/R mapping framework from , which is now part of Jboss. Mybatis is another excellent O/R mapping framework. Currently belongs to a sub-project of apache.

1.1 Introduction to Hibernate

Hibernate provides a relatively complete encapsulation of the database structure. Hibernate's O/R Mapping realizes the mapping between POJOs and database tables, as well as the automatic generation and execution of SQL. Programmers often only need to define the mapping relationship between POJOs and database tables, and then they can complete the 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 according to the specified storage logic and call the JDBC interface to execute it.

1.2 Introduction to MyBatis

The focus of iBATIS lies in the mapping relationship between POJO and SQL. Then through the mapping configuration file, the parameters required by the 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".

development speed

The real master of Hibernate is harder than Mybatis. The Mybatis framework is relatively simple and easy to use, but it is also relatively simple. Personally think that 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 quickly. The current highest version is 4.1.8. Mybatis is relatively calm, with fewer tools, and the current highest version is 3.2.

development effort

Both Hibernate and MyBatis have corresponding code generation tools. Simple and basic DAO layer methods can be generated.

For advanced queries, Mybatis needs to manually write SQL statements and ResultMap. Hibernate has a good mapping mechanism, and developers do not need to care about SQL generation and result mapping, and can focus more on business processes.

Hibernate tuning scheme

  1. Develop a reasonable caching strategy;
  2. Try to use the lazy loading feature;
  3. Adopt a reasonable Session management mechanism;
  4. Use batch fetching and set reasonable batch parameters (batch_size);
  5. Make a reasonable O/R mapping design


Mybatis Tuning Solution

MyBatis is consistent with Hibernate's Session life cycle in terms of Session, and also requires a reasonable Session management mechanism. MyBatis also has a secondary cache mechanism. MyBatis can perform detailed SQL optimization design.

SQL optimization aspects

Hibernate's query will query all fields in the table, which will cost performance. Hibernate can also write its own SQL to specify the fields to be queried, but this destroys the simplicity of Hibernate development. The SQL of Mybatis is written manually, so the fields of the query can be specified as required.

The tuning of Hibernate HQL statements needs to print out the SQL, and Hibernate's SQL is disliked by many people because it is too ugly. MyBatis's SQL is written manually, so it is easy to adjust. But Hibernate has its own log statistics. Mybatis itself does not have log statistics and uses Log4j for logging.

Extensibility

The association between Hibernate and the specific database only needs to be configured in the XML file. All HQL statements have nothing to do with the specific database used, and the portability is very good. All SQL statements in the MyBatis project depend on the database used, so the support of different database types is not good.

object management

Hibernate is a complete object/relational mapping solution, which provides object state management (state management) functions, so that developers no longer need to worry about the details of the underlying database system. That is to say, compared with the common JDBC/SQL persistence layer scheme that needs to manage SQL statements, Hibernate adopts a more natural object-oriented perspective to persist data in Java applications.

In other words, developers using Hibernate should always focus on the state of the object, not the execution of the SQL statement. This part of the details has been taken care of by Hibernate, and only developers need to understand when tuning system performance.

However, MyBatis has no documentation in this section, and users need to manage the objects themselves in detail.

Crawl strategy

Hibernate has a good mechanism for fetching entity-related objects. For each association relationship, you can set whether to delay loading in detail, and provide four modes: association crawling, query crawling, sub-query crawling, and batch crawling. It is configured and handled in detail.

The lazy loading of Mybatis is configured globally.

Hibernate cache

Hibernate's first-level cache is a session cache. To make good use of the first-level cache, it is necessary to manage the life cycle of the session. It is recommended to use a Session in an Action operation. The first level cache needs to strictly manage the session.

The Hibernate second-level cache is a SessionFactory-level cache. SessionFactory's cache is divided into built-in cache and external cache. The built-in cache stores the data (mapping element data and predetermined SQL statements, etc.) contained in some collection properties of the SessionFactory object, which is read-only for the application. The external cache stores a copy of the database data, and its function is similar to that of the first-level cache. In addition to using the memory as the storage medium, the second-level cache can also use external storage devices such as hard disks. The second-level cache is called a process-level cache or a SessionFactory-level cache, which can be shared by all sessions, and its life cycle exists and dies with the life cycle of the SessionFactory.

MyBatis cache

MyBatis includes a very powerful query caching 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 easier to configure.

By default, caching is not enabled, except for local session caching, which enhances monetization and is necessary to handle circular dependencies. To enable L2 cache, you need to add a line to your SQL mapping file: <cache/>

Literally that's it. The effect of this simple statement is as follows:

  1. All select statements in the map statement file will be cached.
  2. All insert, update and delete statements in the map statement file flush the cache.
  3. The cache will be reclaimed using the Least Recently Used (LRU, least recently used) algorithm.
  4. According to the schedule (eg no Flush Interval, no flush interval), the cache will not be flushed in any chronological order.
  5. The cache stores 1024 references to list collections or objects (whatever the query method returns).
  6. The cache is treated as a read/write cache, meaning that object retrievals are 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 caching element properties.

比如: <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>

This more advanced configuration creates a FIFO buffer that is flushed every 60 seconds, holding 512 references to the result object or list, and the returned object is considered read-only, so between callers in different threads Modifying them will cause conflicts. The available eviction strategies are, the default is LRU:

  1. LRU - Least Recently Used: Removes objects that have not been used for the longest time.
  2. FIFO - First In First Out: Remove objects in the order in which they entered the cache.
  3. SOFT - Soft Reference: Remove objects based on garbage collector state and soft reference rules.
  4. WEAK - Weak References: More aggressive removal of objects based on garbage collector state and weak reference rules.

flushInterval can be set to any positive integer, and they represent a reasonable time period in milliseconds. The default is not set, that is, there is no refresh interval, the cache is only refreshed when the statement is called.

size (number of references) can be set to any positive integer, keeping in mind the number of objects you cache and the number of available memory resources in your runtime environment. The default value is 1024.

The readOnly (read-only) property can be set to true or false. A read-only cache will return the same instance of the cache object to all callers. Therefore these objects cannot be modified. This provides a significant performance advantage. Read-write caches return a copy of the cached object (via serialization). This will be slower, but safe, so the default is false.

Same point

In addition to the default cache mechanism of the system, the second-level cache of Hibernate and Mybatis can completely override the cache behavior by implementing your own cache or creating adapters for other third-party cache solutions.

difference

Hibernate's second-level cache configuration is configured in detail in the configuration file generated by SessionFactory, and then configured in the specific table-object mapping.

The second-level cache configuration of MyBatis is configured in detail in each specific table-object mapping, so that different caching mechanisms can be customized for different tables. And Mybatis can share the same cache configuration and instance in the namespace, through Cache-ref.

Compare the two

Because Hibernate has a good management mechanism for query objects, users do not need to care about SQL. Therefore, if there is dirty data when using the second-level cache, the system will report an error and prompt.

In this regard, MyBatis requires special care when using the second-level cache. If the scope of the data update operation cannot be completely determined, avoid the blind use of Cache. Otherwise, the appearance of dirty data will bring great hidden danger to the normal operation of the system.

both are the same

  • Both Hibernate and MyBatis can generate SessionFactory from XML configuration file through SessionFactoryBuider, then SessionFactory generates Session, and finally Session starts to execute transactions and SQL statements. Among them, the life cycle of SessionFactoryBuider, SessionFactory, and Session is similar.
  • Both Hibernate and MyBatis support JDBC and JTA transactions.


Mybatis advantage

  • MyBatis can perform more detailed SQL optimization and reduce query fields.
  • MyBatis is easy to master, while Hibernate has a higher threshold.


Hibernate advantage

  • Hibernate's DAO layer development is simpler than MyBatis, which needs to maintain SQL and result mapping.
  • Hibernate's maintenance and caching of objects is better than MyBatis, and it is more convenient to maintain objects that are added, deleted, and checked.
  • Hibernate database portability is very good, MyBatis database portability is not good, different databases need to write different SQL.
  • Hibernate has a better second-level cache mechanism and can use third-party caches. The caching mechanism provided by MyBatis itself is not good.


Summarize

  • Hibernate is powerful, database-independent, and has strong O/R mapping capabilities. If you are quite proficient in Hibernate and have properly encapsulated Hibernate, the entire persistence layer code of your project will be quite simple, and you need to write very little code. , the development speed is very fast, very cool.
  • The disadvantage of Hibernate is that the learning threshold is not low, the threshold for mastering is higher, and how to design O/R mapping, how to balance performance and object model, and how to use Hibernate well requires your experience and ability are very strong Just do it.
  • iBATIS is easy to get started, and it can be used immediately after learning. It provides automatic object binding for database queries, and continues the good experience of using SQL. It is 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 functions are still missing. Although the data binding code is simplified, the entire underlying database query actually needs to be written by itself, the workload is relatively large, and it is not easy to adapt to rapid database modification.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325820959&siteId=291194637