You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JOOQ在建表时同步声明index索引的正确使用方式是什么

jOOQ 建表时 indexes() 方法的正确使用方式

jOOQ 的 createTable DSL 中提供的 indexes() 方法入参为多个 org.jooq.Index 类型的实例,你可以通过 org.jooq.impl.DSL 类提供的静态工具方法快速构造所需索引。

建议先静态导入DSL下的相关方法,简化代码写法:

import static org.jooq.impl.DSL.*;

以下是完整的使用示例:

context.createTable("user")
    .column("id", INTEGER.identity(true))
    .column("username", VARCHAR(32).nullable(false))
    .column("email", VARCHAR(64).nullable(false))
    .column("register_time", DATETIME.nullable(false))
    .column("is_active", BOOLEAN.nullable(false))
    .constraints(
        primaryKey("id")
    )
    .indexes(
        // 普通单列索引
        index("idx_user_username").on("username"),
        // 普通联合索引,多列按顺序传入即可
        index("idx_user_register_time_email").on("register_time", "email"),
        // 唯一索引
        uniqueIndex("uk_user_email").on("email"),
        // 指定排序规则的索引
        index("idx_user_username_desc").on("username", SortOrder.DESC),
        // 部分/条件索引(仅支持该特性的数据库生效,如PostgreSQL、MySQL 8.0+)
        index("idx_active_user").on("username").where(field("is_active").eq(true))
    )
    .execute();

注意事项

  • 建议显式指定索引名称,符合数据库运维规范,也方便后续需要修改/删除索引时直接定位。
  • 特殊类型的索引(如全文索引、空间索引)需要根据你使用的具体数据库方言,调用对应方言提供的索引构造方法,写法逻辑和上述通用索引一致。

内容的提问来源于stack exchange,提问作者Alisher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:36:04