Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use both JPA and Mybatis

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use JPA and Mybatis at the same time". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use JPA and Mybatis at the same time.

Modeling

@ Entity @ Table (name = "t_order") public class Order {@ Id private String oid; @ Embedded private CustomerVo customer; @ OneToMany (cascade = {CascadeType.ALL}, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "order") private List orderItems;}

The biggest feature of JPA is sqlless, such as the entity definition above, which associates the tables in the database with the types in Java. JPA can automatically create the table structure according to the @ Entity annotation. The Repository interface based on this entity makes it very convenient for JPA users to realize the CRUD of data. Therefore, in projects using JPA, "database design" is rarely mentioned, and people are more concerned with domain modeling than data modeling.

Mybatis users are more likely to use reverse engineering. For example, according to the xml configuration above, the mybatis-generator plug-in can directly translate the table structure into mapper files and entity files.

There is no difference between code first and table first in terms of results, and the difference is the process, so a well-designed system will not be judged simply because of this difference, but from a guiding point of view, there is no doubt that when designing a system, we should consider the relationship between entities and entities, entities and value objects, and the division of domain boundaries, rather than focusing on the design of database table structure first.

From the modeling point of view, JPA's idea of domain modeling is better.

Data update

Talking about the database is naturally inseparable from CRUD, first take a look at the addition, deletion and modification of these data update operations, let's take a look at the general habits of the two frameworks.

There is only one paradigm for data update advocated by JPA, which is divided into three steps:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Mapping from findOne to entity first

Modify entity in memory

Entity whole save

You might argue that @ Query also has the use of nativeQuery and JPQL, but this is not the mainstream usage. JPA especially emphasizes the idea of "overall save", which is closely related to the statefulness emphasized by domain-driven design, that is, it believes that modifications should not be directed at a certain field: "update table set astatb where colomonA=xx", but should be reflected as changes in entities, and save represents the final persistence of entity states.

It is obvious that find before save is also suitable for Mybatis, and the flexibility of Mybatis makes its data update way more blossom. Passers-by A can think that JPA is conformist and inflexible, that Mybatis is unrestrained and indulgent and love freedom; passersby B can also think that JPA format specifications are easy to maintain and Mybatis is not square. There is no more judgment on this point, said posterity.

In terms of personal habits, I still prefer the habit of find before the whole save, not that this is the patent of JPA, Mybatis does not have, but the mandatory of JPA, let me have this habit.

From a data update perspective, JPA can also do this by forcing the use of find+save,mybatis. Winner: none.

Data query

There are two main query methods provided by JPA.

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Simple query: findBy + attribute name

Complex query: JpaSpecificationExecutor

Simple queries provide great convenience in some simple business scenarios. FindBy + attribute names can be automatically translated into sql. Who wouldn't want to write less code?

Complex query is the solution provided by JPA in order to solve the complex query scenario. It simply converts some aggregate functions and join operations of the database into Java methods. Although it achieves sqlless, the code written is smelly and long, and it is not necessarily easy to read and maintain. This is one of the things I like least about JPA, but there is no other way to solve complex queries.

On the other hand, Mybatis can execute any query sql, which is more flexible than JPA. The two most common questions searched by rookies in the database:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

How to do database paging

How to do conditional query

Mybatis can be easily solved.

Never deny complex queries: such as aggregate queries and Join queries. The easiest way to drive a JPA user crazy is to give him a complex query case.

Select a recital brecrum c quot; sum (a) where a=xx and d=xx group by a recital brecrum c

Come on, show. JPA may indeed be able to escape the above sql, but you should know that not all developers are JPA experts, no one cares about how complex queries you solve with JPA, more people care about whether you can finish this complex query before you get off work and go home early.

After going back to the complex data query requirements themselves, we analyze them. We assume that the requirements are reasonable, after all, the complexity of the project is difficult to estimate, there may be 1000 data query requirements JPA can be easily implemented, but there are more than 10 complex queries JPA hold. At this time, you can only write sql obediently. If there is another scenario of conditional query at this time, if else means that you can't even use @ Query, which is completely reduced to the era of JdbcTemplate.

So why not use Mybatis? Mybatis users have never struggled with complex queries, it is simply created for it.

Today, many Mybatis plug-ins can also help users quickly generate basic methods, although you still need to write sql, but this is not a difficult task for developers.

Do not question the possibility of JOIN operations and aggregate functions in high concurrency. In data query scenarios, Mybatis wins completely.

Performance

In essence, the ORM framework has no performance differentiation, because in the end, it is converted to sql and handed over to the database engine to execute, and the performance loss at the ORM level is almost negligible.

But from a practical point of view, Mybatis provides developers with more sql freedom, so it will be more flexible in some scenarios that require sql tuning.

Maintainability

We mentioned earlier that JPA loses the freedom of sql compared with Mybatis, and there must be trade off in everything. On another level, it provides a high-level abstraction and tries to use a unified model to solve problems at the data level. At the same time, sqlless also shields the implementation of the database and shields the compatibility of high and low versions of the database, which provides great convenience for possible database migration and database upgrade.

Use both simultaneously

I will not analyze other details. I believe there are still many points that can be compared, but I believe the main points should have been mentioned above. The comparison of the above dimensions is not my original intention of writing this article, but more to provide some references and suggestions for you to use these two frameworks from the perspective of actual development.

In most scenarios, I am used to using JPA, for example, when designing domain objects, thanks to the forward model of JPA, I will give priority to the relationship between entities and value objects and the boundaries of domain context, rather than paying too much attention to how to design the table structure; in the scenarios of adding, deleting and simple query, the API provided by JPA is already a paradigm engraved in my DNA and is very comfortable to use.

In complex query scenarios, such as

Contains join queries that do not have domain associations

A complex query containing multiple aggregate functions

Other queries that are difficult to implement with JPA

I would choose to use Mybatis, which is a bit like Mybatis as a database view generator. Unswerving JPA fans may question the authenticity of these scenarios and whether they are design loopholes, but as a rule of thumb, even short-term solutions, these scenarios are objective, so listen to me and try to hug Mybatis.

With the popularity of all kinds of storage middleware, such as mongodb and ES, they have replaced part of the database. After rethinking, they are essentially using professional tools to solve the problems of specific scenarios, and the ultimate goal is to liberate productivity. Database, as the oldest and most basic storage component, does carry a lot of things it should not bear, so why let a tool or framework become a gully that limits our imagination?

Neither of the two frameworks is heavy, and with the blessing of springboot, the coexistence of the two can be achieved by introducing a few lines of configuration.

Thank you for your reading, the above is the content of "how to use JPA and Mybatis at the same time". After the study of this article, I believe you have a deeper understanding of how to use JPA and Mybatis at the same time. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report