jOOQ笔记

2019-04-23  本文已影响0人  firefly_
// jOOQ临时表
Table temp = DSL.table(DSL.select(BS_SALESMAN.SALESID, DSL.count().as("count"))
                .from(Tables.BS_SALESMAN)
                .where(BS_SALESMAN.SALESID.eq(1))
                .groupBy(BS_SALESMAN.MOBILE))
                .as("temp");
// 或者使用val
val user = BS_USER.as("user");
// 去重查询
DSL.selectDistinct().from();
// 创建字段
Field<String> field = DSL.field("hello world");
// 创建一个常量值
Param<String> helloWorld = DSL.val("hello world");
// 获取表记录对象
Table<Record> table = DSL.table("bs_user");
// 为真的条件:1=1
Condition condition = DSL.trueCondition();
// 验证DSL.exists()方法
public void exits() throws IOException, SQLException {
        DSLContext dslContext = getdslContext();
        Condition condition = DSL.exists(DSL.select(DSL.field("c_username")));
        Table<Record> table = DSL.table("t_login");
        SelectQuery<Record> selectQuery = dslContext.selectQuery(table);
        selectQuery.addConditions(condition);
        Result<Record> fetch = selectQuery.fetch();
        for (Object aResult : fetch) {
            Record record = (Record) aResult;
            System.out.println(record);
            System.out.println(record.getValue("c_username"));
        }
}
// jOOQ强制索引
DSL.select().from(BS_USER.forceIndex("idx_userid")).where(BS_USER.USERID.eq(1));
// 日期格式化
/**
 * 时间字段转字符串
 *
 * @param field  时间类字段
 * @param format 抓换格式
 * @return 字符型字段
 */
 public static Field<String> dateFormat(Field<?> field, String format) {
    return DSL.field("date_format({0}, {1})", SQLDataType.VARCHAR,
            field, DSL.inline(format));
 }

/**
 * 字符串转时间戳字段
 *
 * @param time   时间
 * @param format 格式
 * @return 时间戳字段
 */
public static Field<Timestamp> stringFormat(String time, String format) {
    return DSL.field("date_format({0}, {1})", SQLDataType.TIMESTAMP,
            time, DSL.inline(format));
}

// dao查询
DSL.select(dateFormat(BS_USER.CREATETM, "%d/%m/%Y").as("createtm"),DSL.COUNT())
   .from(BS_USER)
   .groupBy(dateFormat(BS_USER.CREATETM, "%d/%m/%Y"))
   .fetch();
// case when
DSL.when(US_USER.AGE.lessOrEqual(18), "未成年").otherwise("成年").as("年龄阶段"),
// 联合主键更新
dao.execute(e -> e.insertInto(BS_USER).columns(BS_USER.GROUP_ID
                , BS_USER.USERNAME
                , BS_USER.USERNICKNAME
                , BS_USER.AGE
                , BS_USER.SEX)
                .values(1, "张三", "wind", "23", 1)
        ).onDuplicateKeyUpdate()
       .set(BS_USER.LEVEL, 3)
       // 注意,这里还需调用execute方法才会真正执行
       .execute()
);
上一篇 下一篇

猜你喜欢

热点阅读