Why are people reluctant to use Mybatis after JOOQ is used in the project?

Preface: (welfare at the end of the article)

Today I'd like to introduce a new ORM framework - > jooq. Maybe many friends haven't heard of this framework

Mybatis framework has been used as the persistent layer access framework in Java projects before. However, some recent projects have been developed with JOOQ framework, indicating that they don't want to use mybatis anymore!

Why do you say that? JOOQ is much simpler than Mybatis at the code level, and its performance is excellent.

I'm sure you all have this experience. We use Mybatis to write database related code in project engineering

In order to improve the efficiency of the project, the Mybatis code plug-in is generally used once the database model is designed

(such as: Mybatis generator) to generate entity class code, XML, Mapper and other mapping codes for accessing the Mybatis database, so as to operate and access the database in an object-oriented way as much as possible.

In this way, although the efficiency of the project has been improved a lot, the simplicity and elegance of the code will make people feel particularly wordy

Because the auto generated code is not all you can use in the project

Therefore, some students who pursue code will write SQL code in a relatively simple way.

Write the following code in the @ Mapper interface:

 @Select("select max(t.balance_id) from balance t where t.country=#{country}\n") String selectMaxId(Map<String, String> paramMap); 

And although this way can reduce a lot of useless code

But in the case of complex business logic, this method will obviously reduce the efficiency of development, because it takes us extra time to consider not only the general level of SQL writing

And because of the Java object-oriented programming method, we still need to spend a lot of time to map the database query results to entity objects, so using Mybatis to develop the persistence layer sometimes really makes people love and hate

So is there a new ORM framework that can keep Mybatis flexible and not as heavy as Hibernate?

After all, we all escaped from Hibernate's claws and chose to use Mybatis to this day!

This is the case in the field of software engineering, where there is a pain point, someone will definitely provide solutions, JOOQ is such a product!

JOOQ Introduction (if you think the article is good for you, remember to like it, pay attention to it and share it for three times)

JOOQ is a toolkit based on Java to access relational database. It is lightweight, simple and flexible enough. Through JOOQ, we can easily use java object-oriented syntax to realize various complex SQL.

Compared with the traditional ORM framework, such as Hibernate and Mybatis, JOOQ absorbs the simplicity and security of their operation data, while retaining the flexibility of native SQL. To some extent, JOOQ is more like the middle layer between ORM and JDBC.

JOOQ is relatively small in China

For most of the code farmers who have grown up from SSH or SSM, they may wonder, "is it reliable to use so little?

Here, brother minong can responsibly say JOOQ is reliable

Because manongo has already practiced in several production projects, and it completely uses JOOQ to replace Mybatis as the persistence layer framework in the core payment system, and the concurrent amount of this payment system is also very high

So JOOQ framework itself can stand the test of real business scenarios

Spring boot project integration JOOQ

Next let's take a look at how to integrate and use Joo Q in spring boot projects

First, we introduce JOOQ's state dependency package in the project, as follows:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jooq</artifactId> </dependency> 

JOOQ has good support for Spring Boot, so we just need to introduce the corresponding starter dependency

The specific version is associated with the Spring Boot version, which does not need to be specified here.

Secondly, we need to configure JOOQ's code generation plug-in in the project

In this way JOOQ can automatically generate the required database objects for us when the project is compiled

Configure the Maven plug-in in pom.xml of the project as follows:

 <plugin> <groupId>org.jooq</groupId> <artifactId>jooq-codegen-maven</artifactId> <executions> <execution> <id>default</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <jdbc> <driver>com.mysql.jdbc.Driver</driver> <url>jdbc:mysql://</url> <user>root</user> <password><![CDATA[123456]]></password> </jdbc> <generator> <name>org.jooq.util.DefaultGenerator</name> <generate> <instanceFields>true</instanceFields> <pojos>true</pojos> <daos>true</daos> </generate> <database> <inputSchema>jets</inputSchema> <name>org.jooq.util.mysql.MySQLDatabase</name> <includes>.*</includes> <excludes>schema_version</excludes> </database> <target> <packageName>${app.package}</packageName> <directory>target/generated-sources/jooq</directory></target> </generator> </configuration> </execution> </executions> </plugin> 

After the Maven plug-in is configured, JOOQ is almost integrated with spring boot

If the project JOOQ code plug-in is compiled at this time, the corresponding database operation object will be generated according to the table structure in the database in the target/generated-sources/jooq directory

This process is transparent to developers and we don't need to do anything extra

In the specific business logic

When we need to operate the database, we can easily use the automatically generated code to operate,

For example, we need to perform the insert operation in the business code as follows:

 @Slf4j @Service public class OpenServiceImpl implements OpenService { @Autowired protected DSLContext dslContext; @Override public BalanceChargeTradeResVo balanceChargeTrade(BalanceChargeTradeReqVo balanceChargeTradeReqVo) throws VerifyDataException, BalanceCreateOrderException { BalanceChargeTradeResVo balanceChargeTradeResVo; try { WalletUserBalanceOrderRecord walletUserBalanceOrderRecord = createBalanceChargeOrder(  balanceChargeTradeReqVo);       dslContext.executeInsert(walletUserBalanceOrderRecord);      balanceChargeTradeResVo = BalanceChargeTradeResVo.builder().userId(balanceChargeTradeReqVo.getUserId()) .amount(balanceChargeTradeReqVo.getAmount()).currency(balanceChargeTradeReqVo.getCurrency()) .orderId(walletUserBalanceOrderRecord.getOrderId()).businessType(BusinessType.TOP_UP.getCode()) .build(); return balanceChargeTradeResVo; } catch (Exception e) { throw newBalanceCreateOrderException(ErrorCode.BALANCE_CHARGE_ORDER_ERROR.getCode(), ErrorCode.BALANCE_CHARGE_ORDER_ERROR.getDesc()); } } 

In the above code, we only need to inject the DSLContext object into the service business class

After assembling the automatically generated database objects, execute the executeInsert method to complete the insert operation

If we want to complete the query operation, we can also implement it very simply. The code is as follows:

 @Slf4j @Service public class OpenServiceImpl implements OpenService { @Autowired protected DSLContext dslContext; @Override public BalanceQueryResVo balanceQuery(long userId) throws AccountNoExistException { List<WalletUserBalanceRecord> walletUserBalanceRecordList = dslContext   .selectFrom(WalletUserBalance.WALLET_USER_BALANCE) .where(WalletUserBalance.WALLET_USER_BALANCE.USER_ID       .eq(String.valueOf(userId))).fetchInto(WalletUserBalanceRecord.class); if (walletUserBalanceRecordList == null || walletUserBalanceRecordList.size() <= 0) { throw new AccountNoExistException(ErrorCode.ACCOUNT_NO_EXIST_ERROR.getCode(), ErrorCode.ACCOUNT_NO_EXIST_ERROR.getDesc()); } Optional<WalletUserBalanceRecord> walletUserBalanceRecord = walletUserBalanceRecordList.stream() .filter(o  >o.getAccType().equals(String.valueOf(AccType.CASH_ACCOUNT.getCode()))).findFirst(); BalanceQueryResVo balanceQueryResVo = BalanceQueryResVo.builder().userId(userId) .balance(walletUserBalanceRecordList.stream().mapToInt(o -> o.getBalance().intValue()).sum()) .currency(walletUserBalanceRecord.get().getCurrency()).build(); return balanceQueryResVo; } 

In such as A kind of In the code, we need to specify the table name through the automatically generated class

After the query conditions are assembled in an object - oriented syntax, the query operation can be completed

Here is just a brief introduction to two common database operation methods through JOOQ. For more details, please refer to JOOQ user manual!

In this way, you will find it more convenient and efficient to operate the database

And because automatic code generation is transparent to developers

So the code cleanliness of the whole project is also improved!

PS: you can try JOOQ in your own project. I'm sure you won't regret it!

(of course, this only represents one's own personal view. Everyone will have their own likes and skills, each with its own love.)

The answer is to pay attention to the two-dimensional code below the official account.

Keywords: Java Database Mybatis Spring JDBC

Added by andrewdunstall on Tue, 21 Apr 2020 09:59:26 +0300