The excellence of SpringDataJPA and Mybatis

Click on the blue words to follow us!

A public account that is working hard

All the good-looking people pay attention

28b51ce1ddd7e8fe62c9cc316666a958.png

First of all, to express my personal opinion, JPA must be the first choice.

I personally think that it is not enough to really compare the two frameworks just to discuss the difference between the two and which one is more convenient. To judge a better solution, I think it can be judged from the perspective of software design. I am not familiar with mybatis personally, but the implementation of the JPA specification and springdata, the design concept is absolutely advanced. One solution to the complexity of software development is to follow DDD (DDD is just a means, but not the only means), and I will focus on a few points to talk about how the domain-driven design idea is reflected in the design of JPA, and to start a discussion.

Aggregate Root and Value Object

There are two well-known concepts in domain-driven design, entity (entity) and value object (value object). The characteristic of entity is that it has a life cycle and is identified, while the value object plays a role of decoration, which is immutable and has no identification. In JPA, you need to add the @Entity annotation to the entity class of the database. I believe everyone has noticed that this is not a coincidence.

@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<OrderItem> orderItems;
}

As in the above code, Order is the entity in DDD, and CustomerVo and OrderItem are value objects. Program designers don’t need to care about how the database maps these fields, because in DDD, the work that needs to be done is domain modeling, not data modeling. The meaning of entities and value objects will not be discussed here, but through this we can get a glimpse that the connotation of JPA is not just an ORM framework.

Warehousing

The Repository pattern is another classic pattern in domain-driven design. In the early days, we often named the data access layer: DAO, and in SpringData JPA, it was called Repository (warehousing). This is not a coincidence, but the designer intended it.

Friends who are familiar with SpringData JPA know that when an interface inherits the JpaRepository interface, it automatically has a series of commonly used data operation methods, findAll, findOne, save etc.

public interface OrderRepository extends JpaRepository<Order, String>{
}

So what is the difference between storage and DAO? This will mention some legacy issues, as well as some software design factors. In this SpringForAll topic, I can expect that many will emphasize that SpringData JPA has a convenient and extensible API, like the following:

public interface OrderRepository extends JpaRepository<Order, String>{
findByOrderNoAndXxxx(String orderNo,Xxx xx);
@Transactional
@Modifying(clearAutomatically = true)
@Query("update t_order set order_status =?1 where id=?2")
int updateOrderStatusById(String orderStatus, String id);
}

But what I want to emphasize is that this is a compromise of SpringData JPA, and its support for this feature does not mean its recommended use. Because this is not in line with the concept of domain-driven design. Pay attention to the comparison. The design concept of SpringData JPA is to use Repository as a data warehouse, rather than a collection of database scripts. The findByOrderNoAndXxxx method can be used by the JpaSpecificationExecutor mentioned in the following section Instead, the updateOrderStatusById method can be replaced by findOne + save. Don’t think this is complicated. Just imagine the real business scenario and modify Generally, the operation does not only involve the modification of one field. findOne + save can help you complete more complex business operations without worrying about how we write SQL statements. It really does Domain-oriented development, rather than database SQL-oriented development, object-oriented supporters will inevitably feel that this is more OO.

Specification

As mentioned above, SpringData JPA can use the Specification mode to replace complex SQL script queries such as findByOrderNoAndXxxx. Just imagine, the business is constantly changing, how do you know if there will be one more condition in the future query to become findByOrderNoAndXxxxAndXxxxAndXxxx.... . In order to implement the Specification mode in domain-driven design, SpringData JPA provides a series of Specification interfaces, the most commonly used of which is: JpaSpecificationExecutor

public interface OrderRepository extends JpaRepository<Order, String>, JpaSpecificationExecutor<Order>{
}

Using SpringData JPA to build complex queries (join operations, aggregation operations, etc.) is dependent on the Specification built by JpaSpecificationExecutor. The example is not introduced, it is a bit long.

Please note that the above code is not an example. In a system that really follows the DDD design specification, the OrderRepository interface should be clean without any code. You only need to inherit JpaRepository (responsible for basic CRUD) and JpaSpecificationExecutor (responsible for Specification query ) can be. Of course, SpringData JPA also provides a series of other interfaces, which can be inherited according to specific business scenarios.

Optimistic locking

In order to solve the problem of data concurrency, JPA provides @Version, generally add a Long version field in Entity, with @Version annotation, SpringData JPA also takes this into account. This aspect reflects that the combination of the concept of JPA design and SpringData as an engineering solution has created a great design solution.

Complex multi-table query

Many people favor Mybatis because it provides convenient SQL operations, high degree of freedom, and good encapsulation… SpringData JPA does not support complex SQL well. It does cost a lot to join two tables without entity associations effort. But SpringData JPA doesn’t see this as a problem. Why? Because of the architecture of modern microservices, the databases between each service are isolated, and the join operation across many tables should not be handed over to a single business database. The solution is: use elasticSearch to do view query or Nosql like mongodb to complete. The problem is not a problem.

Summary

If you really walk into JPA and SpringData, you will find that we are not solving a database query problem or using an ORM framework, but are really driving design in the practical field.

(Add again: DDD is just a means, but not the only means)

Second place answer

What Brother Lexburne said is also very good, but I would like to add 2 points to eliminate everyone’s misunderstanding about using spring data jpa
The benefits of spring data jpa I believe everyone understands, that is, the development speed is very fast and very convenient. The place where people are unwilling to use spring data jpa is usually because the sql is not written by themselves, it is uncontrollable, and complex queries are not easy to do. Then I will What I want to say is that for this kind of demand, spring data jpa fully supports it! !

  1. The first way: @query annotation specifies nativeQuery, so that you can use native sql query, the sample code comes from the official document:

    2. What if you can’t handle it with sql alone? What should I do if I have to write logic? You can use the functions provided by Section 3.6.1 of the official document: Customizing individual repositories to implement it. First, look at the code of the official document:

    Let me explain the above code. If you can’t figure out the query method, you can customize the interface, such as CustomizedUserRepository, and its implementation class, and then use your favorite dao framework in this implementation class, such as mybatis, jdbcTemplate, Feel free to, and finally use UserRepository to inherit the CustomizedUserRepository interface, and realize the combined use with other dao frameworks! !

    1. interface CustomizedUserRepository {

    2. void someCustomMethod(User user);

    3. }

    4. class CustomizedUserRepositoryImpl implementsCustomizedUserRepository {

    5. public void someCustomMethod(User user) {

    6. // Your custom implementation

    7. }

    8. }

    9. interface UserRepository extends CrudRepository, CustomizedUserRepository {

    10. // Declare query methods here

    11. }

    12. public interface UserRepository extends JpaRepository {

    13. @Query(value = “SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1”, nativeQuery = true)

    14. User findByEmailAddress(String emailAddress);

    15. }

So let me summarize 1 below. With the two functions introduced above, are you still worried that there will be limitations in using spring data jpa? It will only speed up your development and allow you to use other frameworks in combination. There are only benefits , no harm. .
Finally, let me say one more point. I was looking at es recently, and then I looked at the documents of spring data es. After I scanned it, I found that after learning one of the series of spring data, I was looking at others. I found that I didn’t need it. Take the time to learn. . It can be used directly, yes it is so amazing~~

Third

I have been using hibernate and mybatis since my work. In summary, traditional companies and personal development (maybe just me) like to use jpa, and Internet companies prefer mybatis
Reason: , and mybatis is more flexible. It is determined by the iterative development model. Traditional companies require slow iterations and small project changes. Hibernate can help them do it once and for all. Internet companies pursue fast iterations and rapid changes in requirements. The flexible mybatis is more convenient to modify, and generally every change It will not bring performance degradation. Hibernate often makes the project worse and worse because of adding associations or developers do not understand optimization (the performance is good at the beginning)

1. The official document of mybatis says that it is a semi-automated persistence layer framework, which is more flexible and controllable than the fully automated hibernate
2. The learning cost of mybatis is lower than that of hibernate. The use of hibernate requires a deep understanding of him, especially in terms of caching. As a persistence layer framework, performance is still the first.

Hibernate has a three-level cache. The first-level cache is enabled by default. The second-level cache needs to be manually enabled and configured. The third-level cache can be implemented by integrating popular caching technologies such as redis and ecache in the industry.
Optimization points in the use of hibernate:
1. Cache optimization
2. Lazy loading of associated queries (in development, it is not recommended to use too many foreign keys to associate operations)

The relationship between jpa (Java Persistence API) and hibernate:
Jpa is a specification, and hibernate also follows his specification.
springDataJpa is an encapsulation of repository, which simplifies the operation of repository

Fourth

  • MyBatis is suitable for data analysis OLAP applications, and JPA is suitable for transaction processing OLTP applications.

  • The more complex the business, the more domain modeling is needed, and JPA is the most convenient and flexible way to implement modeling. But if you want to use JPA well, the threshold is relatively high. If you don’t understand DDD, it will be reduced to adding, deleting, modifying and checking.

  • Complicated queries should use the CQRS mode to create a suitable query view through the asynchronous queue, and avoid complex joins through the view, instead of directly querying the domain model.

  • Judging from the current trend, it may be more appropriate to hand over OLAP to NoSQL database

Fifth

I have been using jpa for a while, and mybatis has been used before. I don’t want to say what the difference is, because many people have compared these two frameworks!
From the perspective of domestic open source application frameworks, there are still relatively few people who use jpa as ORM in China. If you switch to hibernate, there will be more people, so the risk you face may be that you will use it, and the people who work with you may not be able to use it. If If you want to cooperate with multiple parties, you must consider this issue!
In terms of flexibility, jpa is more flexible, including basic addition, deletion, modification, query, data relationship, and database switching. It is more flexible than mybatis, but jpa has a higher threshold. In addition, to update data, you need to check the data before updating, and the amount of data is large. , the efficiency of jpa will be lower, and some extra work needs to be done to deal with it at this time!
Now combined with Springboot and Springdata jpa, many things have been simplified. If you are interested and have the ability, you can consider promoting it within the company and in the circle! In the learning stack code cloud warehouse, there are previous things about Springboot integrating JPADemo:

https://gitee.com/learning_stack_database/learnstack.git

Sixth

1. Relatively speaking, the learning cost of jpa is slightly higher than that of mybatis
2. Frequent changes in the company’s business requirements lead to complex table structures. Here, using mybatis is more flexible than jpa

3. As far as the dialect is concerned, after the general company selects the database, the change is minimal, so the advantages of the dialect here can be ignored

Add Xiaobian WeChat, join the technical exchange group or recruitment exchange group