Comparative analysis of hibernate and mybatis

Chapter 1 hibernate and mybatis

Hibernate is the most popular O / R mapping framework at present. It comes from SF Net, now it has become a part of JBoss. Mybatis is another excellent O / R mapping framework. It is currently a subproject of Apache.

Mybatis reference website: http://www.mybatis.org/core/zh/index.html

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

1.1 introduction to hibernate

Hibernate provides a relatively complete package for the 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 only need to define the mapping relationship between POJO and database tables to complete the persistence layer operation through the methods provided by hibernate. Programmers don't even need to be proficient in SQL. Hibernate / OJB will automatically generate the corresponding SQL according to the storage logic and call the JDBC interface for execution.

1.2 introduction to mybatis

Mybatis focuses on the mapping relationship between POJO and SQL. Then map the parameters required by SQL and the returned result fields to the specified POJO by mapping the configuration file. Compared with hibernate "O / R", mybatis is an ORM implementation of "SQL mapping".

Chapter II development comparison

Development speed

The real mastery of Hibernate is more difficult than mybatis. The mybatis framework is relatively simple and easy to use, but it is also relatively simple. Personally, I think to make good use of mybatis, we should first understand hibernate.

Development community

Both hibernate and mybatis are popular persistence layer development frameworks, but the hibernate development community is relatively more lively, supports more tools and updates quickly. At present, the highest version is 4.1 8。 Mybatis is relatively calm and has few tools. The current maximum version is 3.2.

development effort

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. Developers do not need to care about SQL generation and result mapping, and can focus more on business processes.

Chapter III system tuning comparison

Hibernate tuning scheme

1. Formulate reasonable cache strategy;

2. Try to use delayed loading characteristics;

3. Adopt reasonable session management mechanism;

4. Use batch fetching and set reasonable batch_size;

5. Carry out reasonable O / R mapping design

Mybatis tuning scheme

In terms of session, mybatis is consistent with hibernate's session life cycle, and a reasonable session management mechanism is also required. Mybatis also has a second level cache mechanism. Mybatis can carry out detailed SQL optimization design.

SQL optimization

Hibernate query will query all fields in the table, which will have performance consumption. 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 you can specify the query fields as required.

The SQL needs to be printed for the tuning of Hibernate HQL statements, and Hibernate SQL is despised by many people because it is too ugly. The SQL of mybatis 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.

Scalability

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, 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.

Chapter IV object management and capture strategy

Object management

Hibernate is a complete object / relational mapping solution, It provides the function of object state management, so that developers no longer need to pay attention to the details of the underlying database system. In other words, compared with the common JDBC / SQL persistence layer scheme, hibernate adopts a more natural object-oriented perspective to persist the 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. Hibernate has taken charge of this part of the details, which only developers need to understand when tuning the system performance.

Mybatis has no documentation in this section. Users need to manage the objects in detail.

Fetching strategies

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

The delayed loading of mybatis is globally configured.

Chapter V comparison of caching mechanisms

Hibernate cache

Hibernate L1 cache is session cache. To make good use of L1 cache, you need to manage the session life cycle. It is recommended to use a session in an action action. The L1 cache needs to strictly manage the session.

Hibernate L2 cache is a sessionfactory level cache. The cache of sessionfactory is divided into built-in cache and external cache. The built-in cache stores the data contained in some collection attributes of the sessionfactory object (mapping element data, predetermined SQL statements, etc.), which is read-only for applications. The external cache stores a copy of database data, which is similar to the first level cache In addition to using memory as the storage medium, L2 cache can also use external storage devices such as hard disk. L2 cache is called process level cache or sessionfactory level cache. It can be shared by all sessions. Its life cycle exists and dies with the life cycle of sessionfactory.

Mybatis cache

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

By default, the cache is not enabled. In addition to the local session cache, the realization can be enhanced, and it is also necessary to deal with circular dependencies. To enable L2 caching, you need to add a line to your SQL mapping file: < cache / >

Literally. The effect of this simple statement is as follows:

1. All select statements in the mapping statement file will be cached.

2. All insert, update and delete statements in the mapping statement file will refresh the cache.

3. The least recently used (LRU) algorithm will be used to recover the cache.

4. According to the schedule (such as no flush interval, there is no refresh interval), the cache will not be refreshed in any chronological order.

5. The cache will store 1024 references of the list collection or object (no matter what the query method returns).

6. The cache will be regarded as a read / write cache, which means that the object retrieval is not shared and can be safely modified by the caller without interfering with the potential modifications made by other callers or threads.

All these attributes can be modified through the attributes of the cache element.

For example: < cache event = "FIFO" flushinterval = "60000" size = "512" readonly = "true" / >

This more advanced configuration creates a FIFO cache and refreshes it every 60 seconds. It stores 512 references to the result object or list, and the returned objects are considered read-only. Therefore, modifying them between callers in different threads will lead to conflicts. The available retraction strategies are: LRU by default:

1. Least recently used by LRU C: remove objects that have not been used for the longest time.

2. FIFO C first in first out: remove objects in the order they enter the cache.

3. Soft C soft reference: remove objects based on garbage collector status and soft reference rules.

4. Weak C weak reference: more actively remove objects based on garbage collector status and weak reference rules.

Flush intervals 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. The cache is only refreshed 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 read-write cache returns a copy of the cache object (through serialization). This will be slower, but safe, so the default is false.

Same point

In addition to the system default caching mechanism, the secondary cache of hibernate and mybatis can completely override the caching behavior by implementing your own cache or creating adapters for other third-party cache schemes.

difference

The secondary cache configuration of Hibernate is configured in detail in the configuration file generated by sessionfactory, and then configured in the specific table object mapping.

The secondary 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. In addition, mybatis can share the same cache configuration and instances in the namespace through cache Ref.

Comparison between the two

Because hibernate has a good management mechanism for query objects, users do not need to care about SQL. Therefore, when using L2 cache, if dirty data occurs, the system will report an error and prompt.

In this regard, mybatis needs to be very careful when using L2 cache. If the coverage of data update operation cannot be completely 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 VI comparison and summary of hibernate and mybatis

The two have the same point

 both hibernate and mybatis can generate sessionfactory from XML configuration file through sessionfactorybuider, then generate session from sessionfactory, and finally start and execute transactions and SQL statements by session. The lifecycles of sessionfactorybuilder, sessionfactory and session are similar.

Both hibernate and mybatis support JDBC and JTA transaction processing.

Mybatis advantage

 mybatis can perform more detailed SQL optimization and reduce query fields.

 mybatis is easy to master, while hibernate has a high threshold.

Hibernate advantages

 hibernate's Dao layer development is simpler than mybatis. Mybatis needs to maintain SQL and result mapping.

 hibernate maintains and caches objects better than mybatis, and it is convenient to maintain objects added, deleted, modified and queried.

 hibernate database has good portability, but mybatis database has poor portability. Different databases need to write different SQL.

 hibernate has a better secondary cache mechanism and can use third-party cache. The caching mechanism provided by mybatis itself is poor.

 hibernate has powerful functions, good database independence and strong O / R mapping ability. If you are quite proficient in Hibernate and properly encapsulate hibernate, the whole persistence layer code of your project will be quite simple, there is 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. You need to be proficient. You need strong experience and ability in how to design o / R mapping, how to balance performance and object model, and how to make good use of hibernate.

 mybatis is easy to learn and use, provides automatic object binding function for database query, and continues good SQL experience. It is perfect for projects with less high object model requirements.

 the disadvantage of mybatis is that the framework is still relatively simple and the function is still missing. Although the data binding code is simplified, 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 rapid database modification.

summary

The above is the comparative analysis of hibernate and mybatis introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>