Springboot + 持久層框架JOOQ


簡介

官網鏈接

JOOQ是一套持久層框架,主要特點是:

  • 逆向工程,自動根據數據庫結構生成對應的類
  • 流式的API,像寫SQL一樣
    • 提供類型安全的SQL查詢,JOOQ的主要優勢,可以幫助我們在寫SQL時就做檢查
    • 支持幾乎所有DDL,DML
    • 可以內部避免SQL注入安全問題
    • 支持SQL渲染,打印,綁定
  • 使用非常輕便靈活
    • 可以用JPA做大部分簡單的查詢,用JOOQ寫復雜的
    • 可以只用JOOQ作為SQL執行器
    • 可以只用來生成SQL語句(類型安全)
    • 可以只用來處理SQL執行結果
    • 支持Flyway,JAX-RS,JavaFX,Kotlin,Nashorn,Scala,Groovy,NoSQL
    • 支持XML,CSV,JSON,HTML導入導出
    • 支持事物回滾

Springboot+JOOQ初體驗

持久層框架很多,這里參考官網和其他博客用Springboot迅速搭建一個簡單demo看看是否好用

配置依賴

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jooq</artifactId>
</dependency>
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    <plugin>
      <groupId>org.jooq</groupId>
      <artifactId>jooq-codegen-maven</artifactId>
      <executions>
        <execution>
          <goals>
            <goal>generate</goal>
          </goals>
        </execution>
      </executions>
      <dependencies>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.45</version>
        </dependency>
      </dependencies>
      <configuration>
        <!--逆向生成配置文件-->
        <configurationFile>src/main/resources/library.xml</configurationFile>
        <generator>
          <generate>
            <pojos>true</pojos>
            <fluentSetters>true</fluentSetters>
          </generate>
        </generator>
      </configuration>
    </plugin>
  </plugins>
</build>

application.properties

#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

逆向工程

配置文件

在項目的resources目錄下新建library.xml,由於網上JOOQ的教程比較少,且比較老,所以建議去官網拷貝對應版本的配置文件,並酌情修改,否則會無法生成。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.12.0.xsd">
    <!-- Configure the database connection here -->
    <jdbc>
        <driver>com.mysql.cj.jdbc.Driver</driver>
        <url>jdbc:mysql://localhost:3306/demo</url>
        <user>root</user>
        <password>123456</password>
    </jdbc>

    <generator>
        <!-- The default code generator. You can override this one, to generate your own code style.Supported generators:- org.jooq.codegen.JavaGenerator-org.jooq.codegen.ScalaGenerator Defaults to org.jooq.codegen.JavaGenerator -->
        <name>org.jooq.codegen.JavaGenerator</name>

        <database>
            <!-- The database type. The format here is:
                 org.jooq.meta.[database].[database]Database -->
            <name>org.jooq.meta.mysql.MySQLDatabase</name>

            <!-- The database schema (or in the absence of schema support, in your RDBMS this
                 can be the owner, user, database name) to be generated -->
            <inputSchema>demo</inputSchema>

            <!-- All elements that are generated from your schema
                 (A Java regular expression. Use the pipe to separate several expressions)
                 Watch out for case-sensitivity. Depending on your database, this might be important! -->
            <includes>.*</includes>

            <!-- All elements that are excluded from your schema
                 (A Java regular expression. Use the pipe to separate several expressions).
                 Excludes match before includes, i.e. excludes have a higher priority -->
            <excludes></excludes>
        </database>

        <target>
            <!-- The destination package of your generated classes (within the destination directory) -->
            <packageName>com.example.springbootjooq.generated</packageName>

            <!-- The destination directory of your generated classes. Using Maven directory layout here -->
            <directory>src/main/java</directory>
        </target>
    </generator>
</configuration>

自動生成

  • 我們在mysql中創建demo庫,並創建一張User表如下(點的比較快,年齡字段用的varchar勿噴)
mysql> describe user;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(45) | NO   |     | NULL    |                |
| age   | varchar(45) | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
  • 執行compile,會把表結構的抽象,以及表對應的pojo自動生成到指定目錄,然后就可以愉快的coding了
mvn clean compile

Demo

這里實現了最基本的功能

Controller
@RestController
@RequestMapping("/demo/")
public class DemoController {

    @Autowired
    private DemoService service;

    @RequestMapping("/insert/user/{name}/{age}")
    public void insert(@PathVariable String age, @PathVariable String name){
        service.insert(new User().setAge(age).setName(name));
    }

    @RequestMapping("/update/user/{name}/{age}")
    public void update(@PathVariable String age, @PathVariable String name){
        service.update(new User().setAge(age).setName(name));
    }

    @RequestMapping("/delete/user/{id}")
    public void delete(@PathVariable Integer id){
        service.delete(id);
    }

    @RequestMapping("/select/user/{id}")
    public User selectByID(@PathVariable Integer id){
        return service.selectById(id);
    }

    @RequestMapping("/select/user/")
    public List<User> selectByID(){
        return service.selectAll();
    }
}
Service
@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    DSLContext create;

    com.example.springbootjooq.generated.tables.User USER = com.example.springbootjooq.generated.tables.User.USER;

    @Override
    public void delete(int id) {
        create.delete(USER).where(USER.ID.eq(id)).execute();
    }

    @Override
    public void insert(User user) {

        create.insertInto(USER)
                .columns(USER.NAME,USER.AGE)
                .values(user.getName(), user.getAge())
                .execute();
    }

    @Override
    public int update(User user) {
        create.update(USER).set((Record) user);
        return 0;
    }

    @Override
    public User selectById(int id) {
        return create.select(USER.NAME,USER.AGE).from(USER).where(USER.ID.eq(id)).fetchInto(User.class).get(0);
    }

    @Override
    public List<User> selectAll() {
        return create.select().from(USER).fetchInto(User.class);
    }
}

Demo源碼地址

參考

https://blog.csdn.net/weixin_40826349/article/details/89887355


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM