关于springboot:SpringBoot-DB-系列Jooq-之新增记录使用姿势

2次阅读

共计 5053 个字符,预计需要花费 13 分钟才能阅读完成。

【SpringBoot DB 系列】Jooq 之新增记录应用姿态

接下来咱们开始进入 jooq 的增删改查的应用姿态系列,本篇将次要介绍如何利用 jooq 来实现增加数据

<!– more –>

I. 我的项目搭建

本我的项目借助 SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA 进行开发

1. 我的项目依赖

对于如何创立一个 SpringBoot 的我的项目工程,不再本文的形容范畴内,如有趣味能够到文末的集体站点获取

在这个示例工程中,咱们的选用 h2dabase 作为数据库(不便有趣味的小伙伴间接获取工程源码之后,间接测试体验),因而对应的 pom 外围依赖如下

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jooq</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
</dependencies>

2. 数据库初始化

咱们借助 jooq-codegen-maven 插件来主动生成数据库相干的代码,对这一段逻辑感兴趣的小伙伴能够参考博文:【DB 系列】Jooq 代码主动生成

后文中应用的表构造如下

DROP TABLE IF EXISTS poet;

CREATE TABLE poet (
  `id` int NOT NULL,
  `name` varchar(20) NOT NULL default '',
  CONSTRAINT pk_t_poet PRIMARY KEY (ID)
);

DROP TABLE IF EXISTS poetry;
CREATE TABLE poetry (
  `id` int NOT NULL,
  `poet_id` int NOT NULL default '0',
  `title` varchar(128) not null default '',
  `content` varchar(128) not null default '',
  CONSTRAINT pk_t_poetry PRIMARY KEY (ID)
);

3. 配置文件

h2database 的连贯配置如 application.properties

#Database Configuration
spring.datasource.url=jdbc:h2:~/h2-jooq-poet
spring.datasource.username=test
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver


#jOOQ Configuration
spring.jooq.sql-dialect=H2


spring.datasource.initialization-mode=never
spring.datasource.continueOnError=true


##h2 web console 设置
spring.datasource.platform=h2
#进行该配置后,h2 web consloe 就能够在近程拜访了。否则只能在本机拜访。spring.h2.console.settings.web-allow-others=true
#进行该配置,你就能够通过 YOUR_URL/h2 拜访 h2 web consloe
spring.h2.console.path=/h2
#进行该配置,程序开启时就会启动 h2 web consloe
spring.h2.console.enabled=true

II. 新增记录

接下来咱们进入正式的数据插入的应用姿态介绍,一般来说新增数据会辨别单个和批量两种形式,上面咱们别离进行介绍

1. Record 实体类新增形式

在 jooq 中,借助主动生成的 Record 类来实现新增是最简略的 case,如下


private static final PoetTB table = PoetTB.POET;
@Autowired
private DSLContext dsl;

/**
 * 新增记录
 *
 * @param id
 * @param name
 * @return
 */
public boolean save(int id, String name) {PoetPO record = dsl.newRecord(table);
    record.setId(id);
    record.setName(name);
    return record.insert() > 0;}

留神:

  • 实体类的创立形式:PoetPO record = dsl.newRecord(table);,不要间接 new 一个对象进去应用

2. 链式写法

上面介绍的这种写法和 sql 十分类似,也是我集体用的比拟多的形式,特点就是高深莫测

public boolean save2(int id, String name) {return dsl.insertInto(table).set(table.ID, id).set(table.NAME, name).execute() > 0;}

3. InsertQuery 形式

下面两种写法比拟常见,而间接应用 InsertQuery 的形式,在理论的业务开发中可能并没有下面的优雅,但某些非凡场景下还是很有用的

/**
 * 不应用主动生成的代码来原生插入数据
 *
 * @param id
 * @param name
 * @return
 */
public boolean save3(int id, String name) {// 当不应用主动生成的对象时,table 能够用 DSL.table()指定,列能够用 DSL.field()指定
    InsertQuery insertQuery = dsl.insertQuery(DSL.table("poet"));
    insertQuery.addValue(DSL.field("id", Integer.class), id);
    insertQuery.addValue(DSL.field("name", String.class), name);
    return insertQuery.execute() > 0;}

留神一下下面的用法,InsertQuery自身的应用没有什么值得说到的,重点在下面的实现中,并没有利用主动生成的代码,如

  • table: DSL.table(表名)
  • field: DSL.field(列名,类型)

通过下面的的 case,咱们能够晓得在不主动生成 DB 对应的代码前提下,如何进行数据库的操作

4. Record 实体批量保留

借助 dsl.batchInsert 来批量增加实体,属于最根底的应用姿态了

private PoetPO bo2po(PoetBO bo) {PoetPO po = dsl.newRecord(table);
    po.setId(bo.getId());
    po.setName(bo.getName());
    return po;
}

/**
 * 通过 Record 执行批量增加
 *
 * @param list
 * @return
 */
public boolean batchSave(List<PoetBO> list) {List<PoetPO> poList = list.stream().map(this::bo2po).collect(Collectors.toList());
    int[] ans = dsl.batchInsert(poList).execute();
    System.out.println(JSON.toJSONString(ans));
    return true;
}

5. 链式批量保留

同样是类 sql 的链式插入方式,须要留神一下与后面的单条记录的链式插入的区别,上面这种写法和 sql 的批量插入的写法及其类似

/**
 * 类 sql 写法,批量增加
 *
 * @param list
 * @return
 */
public boolean batchSave2(List<PoetBO> list) {InsertValuesStep2<PoetPO, Integer, String> step = dsl.insertInto(table).columns(table.ID, table.NAME);
    for (PoetBO bo : list) {step.values(bo.getId(), bo.getName());
    }
    return step.execute() > 0;}

6. InsertQuery 批量保留

下面介绍了 InsetQuery 的单条插入方式,上面的批量写法基本上没有太大的区别

/**
 * 不基于主动生成的代码,来批量增加数据
 *
 * @param list
 * @return
 */
public boolean batchSave3(List<PoetBO> list) {InsertQuery insertQuery = dsl.insertQuery(DSL.table("poet"));
    for (PoetBO bo : list) {insertQuery.addValue(DSL.field("id", Integer.class), bo.getId());
        insertQuery.addValue(DSL.field("name", String.class), bo.getName());
        insertQuery.newRecord();}

    return insertQuery.execute() > 0;}

7. 测试 case

接下来测试一下下面的 6 个办法执行

public void test() {this.save(11, "一灰");
    this.save2(12, "一灰灰");
    this.save3(13, "一灰灰 Blog");


    this.batchSave(Arrays.asList(new PoetBO(14, "yh"), new PoetBO(15, "yhh")));
    this.batchSave2(Arrays.asList(new PoetBO(16, "yihui"), new PoetBO(17, "yihuihui")));
    this.batchSave3(Arrays.asList(new PoetBO(18, "YiHui"), new PoetBO(19, "YiHuiBlog")));

    RecordMapper<PoetPO, PoetBO> mapper =
            dsl.configuration().recordMapperProvider().provide(table.recordType(), PoetBO.class);
    List<PoetBO> result = dsl.selectFrom(table).fetch().map(mapper);
    System.out.println(result);
}

输入后果如下

[1,1]
[PoetBO (1, 李白), PoetBO (2, 艾可翁), PoetBO (11, 一灰), PoetBO (12, 一灰灰), PoetBO (13, 一灰灰 Blog), PoetBO (14, yh), PoetBO (15, yhh), PoetBO (16, yihui), PoetBO (17, yihuihui), PoetBO (18, YiHui), PoetBO (19, YiHuiBlog)]

II. 其余

0. 我的项目

系列博文

  • 【SpringBoot DB 系列】Jooq 代码主动生成
  • 【SpringBoot DB 系列】Jooq 初体验

我的项目源码

  • 工程:https://github.com/liuyueyi/spring-boot-demo
  • 我的项目源码:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/108-jooq-curd

1. 一灰灰 Blog

尽信书则不如,以上内容,纯属一家之言,因集体能力无限,不免有疏漏和谬误之处,如发现 bug 或者有更好的倡议,欢送批评指正,不吝感谢

上面一灰灰的集体博客,记录所有学习和工作中的博文,欢送大家前去逛逛

  • 一灰灰 Blog 集体博客 https://blog.hhui.top
  • 一灰灰 Blog-Spring 专题博客 http://spring.hhui.top

正文完
 0