Comparison between MyBatis and Hibernate

  • 2020-04-01 04:37:48
  • OfStack

Chapter 1 Hibernate and MyBatis

Hibernate, the most popular O/R mapping framework, originated in sf.net and is now part of Jboss. Mybatis is another excellent O/R mapping framework. Currently a subproject of apache.

MyBatis resources website: (link: http://www.mybatis.org/core/zh/index.html)

Hibernate resources: (link: http://docs.jboss.org/hibernate/core/3.6/reference/zh-CN/html_single/ http://

1.1 introduction of Hibernate

Hibernate provides a relatively complete encapsulation of database structure. Hibernate's O/R Mapping realizes the Mapping between POJO and database tables, as well as the automatic generation and execution of SQL. Programmers often need only define the mapping of pojos to database tables to complete persistence layer operations through methods provided by Hibernate. The programmer doesn't even need to be proficient with SQL, Hibernate/OJB automatically generates the corresponding SQL and calls the JDBC interface for execution based on the specified storage logic.

1.2 introduction of MyBatis

IBATIS focuses on the mapping between pojos and SQL. The parameters required for the SQL, along with the returned result fields, are then mapped to the specified POJO by mapping the configuration file. Compared with Hibernate "O/R", iBATIS is an ORM implementation of "Sql Mapping".

Chapter two development comparison

Speed of development

The true grasp of Hibernate is more difficult than Mybatis. Mybatis framework is relatively simple and easy to use, but also relatively simple. I think to use Mybatis or the first to understand Hibernate.

The development community

Hibernate and Mybatis are both popular persistence layer development frameworks, but the Hibernate development community is relatively lively, there are many supported tools, updates are fast, the current top version of 4.1.8. Mybatis is relatively calm, fewer tools, the current top version 3.2.

Development workload

Hibernate and MyBatis have corresponding code generation tools. You can generate simple basic DAO layer methods.

For advanced queries, Mybatis requires manual writing of SQL statements, as well as a ResultMap. Hibernate has a good mapping mechanism, so developers don't need to worry about SQL generation and result mapping, and can focus more on business processes.

Chapter 3 system tuning comparison

Hibernate tuning scheme
Develop a reasonable caching strategy;
Use lazy loading feature as much as possible.
Reasonable Session management mechanism is adopted.
Using batch fetching, set reasonable batch parameters (batch_size);
Carry out reasonable O/R mapping design

Mybatis tuning scheme

MyBatis is consistent with Hibernate's Session life cycle in terms of Session, and it also needs a reasonable Session management mechanism. MyBatis also has a secondary caching mechanism. MyBatis can carry out detailed SQL optimization design.

SQL optimization

Hibernate queries query all the fields in the table, which can be a performance drain. Hibernate can also write its own SQL to specify the fields to query, but this breaks the simplicity of Hibernate development. The SQL for Mybatis is written manually, so you can specify the fields of the query as required.

Tuning Hibernate HQL statements requires printing SQL, and Hibernate SQL is detested by many as too ugly. MyBatis SQL is written manually so it is easy to adjust. But Hibernate has its own log statistics. Mybatis itself does not carry log statistics, using Log4j for logging.

extensibility

The association of Hibernate with a specific database can only be configured in an XML file, and all HQL statements are independent of the specific database used, which makes it very portable. All SQL statements in the MyBatis project are dependent on the database used, so the support for different database types is not good.

Chapter four object management and fetching strategy

The object management

Hibernate is a complete object/relational mapping solution that provides state management of objects, eliminating the need for developers to pay attention to the details of the underlying database system. That is, Hibernate takes a more natural object-oriented perspective for persisting data in Java applications, compared to the common JDBC/SQL persistence layer scenario where SQL statements need to be managed.

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

There is no documentation for MyBatis in this block, so the user needs to conduct detailed management of the object itself.

Fetching strategy

Hibernate has a good mechanism for fetching entity association objects. For each association relationship can be set in detail whether lazy loading, and provides four modes of association fetching, query fetching, subquery fetching, and batch fetching. It is configured and handled in detail.

The lazy load of Mybatis is globally configured.

Chapter five compares caching mechanisms

Hibernate cache

Hibernate level 1 cache is the Session cache, the use of the level 1 cache needs to manage the Session life cycle. It is recommended that you use a Session in an Action. Level 1 caching requires strict Session management.

The Hibernate level 2 cache is a sessionfactory-level cache. The SessionFactory cache is divided into built-in and external caches. The built-in cache holds the data contained in some collection attributes of the SessionFactory object (mapping data, scheduled SQL statements, etc.), which is read-only to the application. External cache stores a copy of database data, which is similar to the first-level cache. In addition to using memory as storage medium, second-level cache can also use external storage devices such as hard disk. A second-level cache is called a process-level cache or a sessionfactory-level cache, which can be Shared by all sessions, and whose life cycle lives and dies with the life cycle of the SessionFactory.

MyBatis cache

MyBatis includes a very powerful query caching feature that can be easily configured and customized. Many of the improvements to the cache implementation in MyBatis 3 have already been implemented, making it more powerful and easier to configure.

Caching is not turned on by default, except for local session caching, which enhances liquidity and is required to handle loop dependencies. To enable level 2 caching, you need to add a line to your SQL mapping file: < The cache / >

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 flush the cache.
The cache is retrieved using the Least Recently Used(LRU) algorithm.
Depending on the schedule (such as the no Flush Interval, where there is no Flush Interval), the cache is not flushed 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 a read/write cache, meaning that the object retrieval is not Shared and can be safely modified by the caller without interfering with potential changes made by other callers or threads.
All of these attributes can be modified by caching the attributes of the element.

For example: < Cache eviction="FIFO" flushInterval=" 60,000 "size="512" readOnly="true"/>

This more advanced configuration creates a FIFO cache and refreshes it every 60 seconds, storing 512 references to the resulting object or list, and returning objects that are considered read-only, so modifying them between callers in different threads causes conflicts. The available recovery strategies are, by default, LRU:

Least recently used LRU wicks: removes objects that have not been used for the longest time.
FIFO first in first out: remove objects in the order they enter the cache.
SOFT references: removes objects based on garbage collector state and SOFT reference rules.
WEAK reference: more actively removes objects based on garbage collector state and WEAK reference rules.
FlushInterval (flushInterval) can be set to any positive integer, and they represent a reasonable period of time in milliseconds. The default is not set, that is, there is no refresh interval, and the cache is only refreshed when the statement is called.

Size (number of references) can be set to any positive integer, bearing in mind the number of objects you cache and the number of memory resources available for 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 cached object to all callers. So these objects cannot be modified. This provides important performance advantages. A read-write cache returns a copy of the cache object (through serialization). This is slower, but safe, so the default is false.

The same

In addition to using the system's default caching mechanism, both Hibernate and Mybatis can fully override caching behavior by implementing your own caching or creating adapters for other third-party caching schemes.

The difference between

Hibernate's second-level cache configuration is configured in detail in a configuration file generated by the SessionFactory and then configured in a specific table-object map to be that kind of cache.

The secondary cache configuration of MyBatis is configured in detail in each specific table-object map 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.

Both are

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

And MyBatis in this respect, the use of the secondary cache needs to be particularly careful. Avoid blind use of the Cache if you are not completely sure of the extent of the data update operation. Otherwise, the appearance of dirty data will bring great hidden trouble to the normal operation of the system.

Chapter six Hibernate and Mybatis comparison and summary

The same thing

Both Hibernate and MyBatis can generate SessionFactory by SessionFactoryBuider from the XML configuration file, then generate Session by SessionFactory, and finally start the execution of transactions and SQL statements by Session. Where SessionFactoryBuider, SessionFactory, Session life cycle are the same.

Both Hibernate and MyBatis support JDBC and JTA transaction processing.

Mybatis advantage

MyBatis can perform more detailed SQL optimization, which can reduce query fields.

MyBatis is easy to master, and 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 object maintenance and cache is better than MyBatis, to add, delete, change and check the maintenance of the object to be convenient.

Hibernate database portability is good, the database portability of MyBatis is not good, different databases need to write different SQL.

Hibernate has a better second-level caching mechanism and can use third-party caching. MyBatis itself provides a poor caching mechanism.

Summary of others

Hibernate is powerful, database independence is good, O/R mapping ability is strong, if you are quite proficient in Hibernate, and the appropriate encapsulation of Hibernate, then your project the entire persistence layer code will be quite simple, need to write very little code, development speed is very fast, very cool.

The disadvantage of Hibernate is that the learning threshold is not low, the proficiency threshold is higher, and how to design O/R mapping, how to balance the performance and the object model, and how to use Hibernate needs your experience and ability to be very strong.

IBATIS is simple to get started, ready to use, provides automatic object binding for database queries, and continues a good SQL experience, perfect for projects with less demanding object models.

The disadvantage of iBATIS is that the framework is still relatively simple and the function is still missing. Although it simplifies the data binding code, the whole underlying database query actually needs to be written by itself, the workload is relatively large, and it is not easy to adapt to the rapid database modification.


Related articles: