Have your cake and eat it: Hibernate and Mybatis coexist

For a long time, there have been many arguments on the Internet about the merits of Hibernate and Mybatis. Neither of the two camps can convince the other. Everyone’s reasons are very reasonable. Today, I share the topic of using Hibernate and Mybatis ORM frameworks in one project.

As a developer, there is no need to spend too much time arguing that technology is useless. When you start blaming one framework for being rubbish and another for being the best, you are implicitly showing that you don’t have a deep understanding of that framework. There is no right or wrong framework, only the right or better choice for the project. Any framework has its own range of capabilities. Take Hibernate and Mybatis as an example. Hibernate encapsulates a lot of useful apis for developers, which reduces the difficulty and complexity of database operation, and also reduces the number of template code. But Hibernate leaves much less room for developers than Mybatis; The Mybatis framework is flexible to use, allowing developers to customize queries, but with the added amount of template code, it doesn’t seem as convenient as Hibernate. The two frameworks make trade-offs and compromises on the two indicators of convenience and flexibility, which cannot be said to be the fault of the frameworks. For a framework, you need to have your own domain of focus and design vision, it is impossible to do everything.

With any technology framework, you need to fit your actual business needs and your own technical capabilities. Don’t blindly criticize a framework when you don’t have a deep understanding of a technology or current business needs that don’t fit into the framework. Today, I will no longer compare the advantages and disadvantages of Hibernate and Mybatis, but give a more moderate solution, which integrates the two ORM frameworks in one project at the same time.

First, prepare the development environment

If you want to run the source code in this article successfully, you need to meet the following conditions:

  • 1. JDK: JDK 1.8.x or later
  • 2. Maven: Maven 3.x or later
  • Git: version control tool. Choose one you like
  • 4, IDE: choose a code editor you like, such as STS, IntelliJ IDEA. The author used IntelliJ IDEA
  • 5. Databases: Select a database system that you are familiar with. The author used the MySQL 5.1.x database system in this article

If you want to get the source code for this share to debug, you can find the source code repository link at the end of this article

Ii. Building the project

2-1. Introducing dependencies

In order to build the project quickly, the author uses Spring Boot to build the project, and at the same time uses the dependency packages added to Spring Data JPA and Mybatis two ORM frameworks. Hibernate is an implementation of the JPA standard, and Spring Data JPA is an abstraction of JPA Data access. With Spring Data JPA, Hibernate framework can be easily used.

You can use Spring Initializer to initialize projects or use the Spring Initializer function provided with IDEA to build projects. After the project is built, the configuration in the POM. XML file is as follows (including but not limited to the dependencies described in this article) :

2-2, define entity class – user.java

To demonstrate how to use both Hibernate and Mybatis to operate a database, we need to provide an entity class user.java that looks like this:

Description:

The Lombok plug-in is used in this demo project, which allows developers to write less template code and speed up development. The @data annotation automatically generates getters, setters, and toString methods for class properties. @NoargsConstructor automatically generates a no-argument constructor for a class, while @AllargsConstructor generates a constructor with all properties.

2-3. Define data persistence interfaces

In this tutorial, you will use Spring Data JPA to perform write operations such as add, modify, and delete; Use Mybatis to complete the read operation, such as query according to user ID, query all users, etc. Spring Data JPA and MyBatis are located in com.ramostear.hm.orm package, Spring Data JPA persistence interface is quite simple, inherit JpaRepository class, code as follows:

JPA is only responsible for write operations, so we can directly inherit and use the API provided by JpaRepository. There is no need to define other interface methods.

The following is the mapping interface of Mybatis, defining two methods: query user information according to ID and query all user information. The code looks like this:

Description:

The important things to note about this interface are the @Component and @mapper annotations. After the @Component annotation annotates this interface, Spring automatically scans and configures this class. The @mapper annotation allows Spring to manage the Mapper DAO.

After defining the Mybatis mapping interface, you need to provide an XML configuration file for querying the database. This file is located in the resources/mapper folder. The complete code for usermapper.xml is as follows:

2-4. Define UserService

The UserService interface provides three methods: saving user information, querying users by ID, and querying all users. The UserService interface code is as follows:

In the implementation class of the UserService interface, you need to inject both UserRepository and UserMapper dependencies. We use constructors to inject these two dependencies. The code is as follows:

Description:

The @transactional annotation is used to set the transaction control for each method. The @Service annotation declares that the class is a Service provider class and sets the name of the Bean object to “userService” when the class is initialized by Spring.

2-5. Define the controller

Finally, provide a controller to handle the client’s related requests. In the controller, three request processing methods are provided to process the new user on the client, query the user by ID, and query the request of all users. The controller code is as follows:

Description:

In this tutorial, all dependency injection uses constructors to inject dependencies in order to encode the WARNING message IDEA.

Configure Hibernate and Mybatis

There are many tutorials on how to configure Hibernate and Mybatis in a Spring Boot project, but there are few articles on how to configure Hibernate and Mybatis together. Some of them use Java code to configure the two ORM frameworks. A multi-data source approach was adopted to integrate the two frameworks. Integrating the two frameworks is not as difficult as you might think. Just add a few lines of code to your application.yml or application.properties configuration file. Yml configuration file is used as an example. The configuration code is as follows:

Is not very simple, and for not too much complex configuration, this is a simpler way to integrate. Hibernate and Mybatis share the same data source. If you are a JPA fan and want to use Mybatis, you only need to add Mybatis configuration.

Four, test,

Now that the project is set up, we will use the Postman test tool to test the Controller’s three methods to verify that the two ORM frameworks can coexist in the same project.

First, test POST http://localhost/users to verify that Hibernate can successfully persist user information. Open the Postman tool, enter http://localhost/users in the address box, select POST as the request mode, and enter the following information in the Body box:

{
	"username":"Tan Zhaohong"."alias":"ramostear"."age":28
}
Copy the code

Click the “Send” button to Send the request and observe the server response information. The test results are as shown in the figure below:

You can see that the server successfully returns the user information, and the user ID is 3. Next, we request GET http://localhost/users/3 to verify whether Mybatis can successfully query the user information. The test results are as follows:

The server successfully returns user information with user ID=3:

{
  "id": 3."username": "Tan Zhaohong"."alias": "ramostear"."age": 28
}
Copy the code

This proves that Hibernate and Mybatis can work normally in the same project, and the integration scheme is effective, which solves the problem of Hibernate and Mybatis coexistence in the same project.

Five, the summary

This course verifies the feasibility of using Hibernate and Mybatis two ORM frameworks at the same time, and adopts a relatively simple way to integrate the two frameworks, abandon the complex configuration of multiple data sources, and quickly realize the needs of using the two frameworks.

Does it make sense to use both ORM frameworks on a project? My answer is yes. On the other hand, when using Mybatis alone, developers need to manually or with the help of other tools to generate database table information, and the integration scheme in this paper is adopted. Mybatis can use the ability of JPA to generate database tables automatically, so as to simplify the steps of using Mybatis. Finally, for some systems with more read than write operations, the two frameworks can be used at the same time. For modules with less write operations, Spring Data JPA can be used to quickly complete the implementation of related functions. For the part of read operations, Mybatis can be used to optimize the query statement. The complementary advantages between the two can further improve the development efficiency and system performance.

Share the content of the source code warehouse address:

Github.com/ramostear/o…