Springboot整合JOOQ

jOOQ是一个基于Java的编写SQL的工具包,具有:简单,轻量,函数式编程写SQL等独特优势,非常适合敏捷快速迭代开发。

SQL语句:

SELECT AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, COUNT(*)
    FROM AUTHOR
    JOIN BOOK ON AUTHOR.ID = BOOK.AUTHOR_ID
   WHERE BOOK.LANGUAGE = 'DE'
     AND BOOK.PUBLISHED > DATE '2008-01-01'
GROUP BY AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME
  HAVING COUNT(*) > 5
ORDER BY AUTHOR.LAST_NAME ASC NULLS FIRST
   LIMIT 2
  OFFSET 1  

Java的代码:

create.select(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, count())
      .from(AUTHOR)
      .join(BOOK).on(AUTHOR.ID.equal(BOOK.AUTHOR_ID))
      .where(BOOK.LANGUAGE.eq("DE"))
      .and(BOOK.PUBLISHED.gt(date("2008-01-01")))
      .groupBy(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
      .having(count().gt(5))
      .orderBy(AUTHOR.LAST_NAME.asc().nullsFirst())
      .limit(2)
      .offset(1)
1. pom修改
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>springboot-jooq</groupId>
    <artifactId>springboot-jooq</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-jooq</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jooq</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

        <!-- 阿里巴巴fastjson,解析json视图 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.jooq</groupId>
            <artifactId>jooq-meta</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jooq</groupId>
            <artifactId>jooq-codegen</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.jooq</groupId>
                <artifactId>jooq-codegen-maven</artifactId>
                <version>${jooq.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <configurationFile>src/main/resources/JooqConfig.xml</configurationFile>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>
逆向工程
2.1逆向配置文件

JooqConfig.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
    <jdbc>
        <driver>com.mysql.jdbc.Driver</driver>
        <url>jdbc:mysql://localhost:3306/user</url>
        <user>root</user>
        <password>root</password>
    </jdbc>
    <generator>
        <!-- 代码生成器 -->
        <name>org.jooq.util.JavaGenerator</name>
        <database>
            <!--下面这两行是为view也生成代码的关键-->
            <!--force generating id'sfor everything in public schema, that has an 'id' field-->
            <syntheticPrimaryKeys>public\..*\.id</syntheticPrimaryKeys>
            <!--name for fake primary key-->
            <overridePrimaryKeys>override_primmary_key</overridePrimaryKeys>

            <name>org.jooq.util.mysql.MySQLDatabase</name>

            <!--include和exclude用于控制为数据库中哪些表生成代码-->
            <includes>.*</includes>
            <!--<excludes></excludes>-->

            <!--数据库名称-->
            <inputSchema>user</inputSchema>
        </database>

        <generate>
            <!--生成dao和pojo-->
            <daos>true</daos>
            <pojos>true</pojos>
            <!--把数据库时间类型映射到java 8时间类型-->
            <javaTimeTypes>true</javaTimeTypes>
            <!--<interfaces>true</interfaces>-->
            <!--不在生成的代码中添加spring注释,比如@Repository-->
            <springAnnotations>false</springAnnotations>
        </generate>

        <target>
            <!--生成代码文件的包名及放置目录-->
            <packageName>com.generator</packageName>
            <directory>src/main/java</directory>
        </target>
    </generator>
</configuration>
2.2 mvn执行逆向工程

img

先进行clean再编,然后我们就会发现,生成了很多个类

img

如果你看到了这些,那么恭喜。你的jooq环境搭建成功了!

三层架构
服务接口

UserService .java

package com.fantj.service;

import com.fantj.pojos.User;

import java.util.Iterator;

/**
 * Created by Fant.J.
 */
public interface UserService {
    /** 删除 */
    public void delete(int id);
    /** 增加*/
    public void insert(User user);
    /** 更新*/
    public int update(User user);
    /** 查询单个*/
    public User selectById(int id);
    /** 查询全部列表*/
    public Iterator<User> selectAll(int pageNum, int pageSize);
}
serviceImpl

UserServiceImpl .java

package com.fantj.service.impl;

/**
 * Created by Fant.J.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    DSLContext dsl;
/*
    @Autowired
    private UserDao userDao;*/

    com.generator.tables.User u =  User.USER_.as("u");
    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(int id) {
        dsl.delete(u).where(u.ID.eq(id));
    }

    /**
     * 增加
     *
     * @param user
     */
    @Override
    public void insert(com.fantj.pojos.User user) {
        dsl.insertInto(u).
                columns(u.ADDRESS,u.BIRTHDAY,u.SEX,u.USERNAME).
                values(user.getAddress(),user.getBirthday(),user.getSex(),user.getUsername())
                .execute();
    }

    /**
     * 更新
     *
     * @param user
     */
    @Override
    public int update(com.fantj.pojos.User user) {
        dsl.update(u).set((Record) user);
        return 0;
    }

    /**
     * 查询单个
     *
     * @param id
     */
    @Override
    public com.fantj.pojos.User selectById(int id) {
        Result result =  dsl.select(u.ADDRESS,u.BIRTHDAY,u.ID,u.SEX,u.USERNAME)
                .from(u)
                .where(u.ID.eq(id)).fetch();
        System.out.println(result.get(0).toString());
        String className = result.get(0).getClass().getName();
        System.out.println(className);
        com.fantj.pojos.User user = new com.fantj.pojos.User();
        return null;
        /*com.fantj.pojos.User user1 = userDao.findById(id);
        return user1;*/
    }

    /**
     * 查询全部列表
     *  @param pageNum
     * @param pageSize
     */
    @Override
    public Iterator<com.fantj.pojos.User> selectAll(int pageNum, int pageSize) {
        Result result = dsl.select().from(u).fetch();

        return result.iterator();
    }
}

我对几段代码做点解释

  @Autowired
    DSLContext dsl;

这里是注入DSL上下文对象,DSLContextl里面有连接对象,大概猜测的话应该是与数据库连接交互的一个对象。

com.generator.tables.User u =  User.USER_.as("u");

这段代码的意思是给用户表重命名u。(类似sql语句中的用户为你)。
但是注意一点,这个用户类是逆向生成的表包下的,不是pojos包下的用户实体类。
(逆向工程它会生成两个用户类一个在的POJO下,一个。再表下)。

还有,我在这里只测试了一个方法selectById(),别的我没有测试,大概应该差不多。
好了,大家让看看方法selectById()的运行查询查询结果。

img

控制台打印分别对应上面代码中的这两个语句

System.out.println(result.get(0).toString());  //获取result对象中的第一个对象并打印toString
String className = result.get(0).getClass().getName();  //获取Result第一个对象的类类型
System.out.println(className);

我目前还没有把org.jooq.impl.RecordImpl这个对象转换成我们想要的POJO的包下的用户实体类。
但是查询的功能是实现了,希望有能力大佬再研究和试试。

。我也试过用它逆向生成的userDAO的(我再上面代码中注释掉的)结果报错:
org.jooq.exception.DetachedException: Cannot execute query. No Connection configured
。意思是没有获取到连接配置信息这块也没能搞懂希望大佬也能在下面评论。

调节器

UserController .java

package com.fantj.controller;

/**
 * Created by Fant.J.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET,value = "/delete/{id}")
    public void delete(@PathVariable("id")int id){
        userService.delete(id);
    }

    @RequestMapping(method = RequestMethod.POST,value = "/insert")
    public void insert(User user){
        userService.insert(user);
    }
    @RequestMapping(method = RequestMethod.POST,value = "/update/{id}")
    public void update(@RequestParam User user){
        userService.update(user);
    }

    @RequestMapping(method = RequestMethod.GET,value = "/{id}/select")
    public User select(@PathVariable("id")int id){
        return userService.selectById(id);
    }

    @RequestMapping(method = RequestMethod.GET,value = "/selectAll/{pageNum}/{pageSize}")
    public List<User> selectAll(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
        Iterator<User> userIterator = userService.selectAll(pageNum, pageSize);
        List<User> list = new ArrayList<>();
        while(userIterator.hasNext()){
            list.add(userIterator.next());
        }
        return list;
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值