使用JOOQ更新多个表

时间:2015-10-21 18:25:08

标签: java mysql join subquery jooq

此处jooq的问题在于它不支持joinupdates,而且还支持多个表的更新。

我找到了转换此查询的方法:

   String query =   "UPDATE knowCRM.customer_did cd ";
        query +=    " LEFT JOIN knowCRM.know_service ks";
        query +=    " ON ks.id = cd.customer_service_id";
        query +=    " LEFT JOIN knowCRM.customer_flags cf";
        query +=    " ON ks.service_owner_id = cf.account_number";
        query +=    " SET cd.is_cli_number= 1, cf.is_cli_number = '0'";
        query +=    " WHERE ks.service_owner_id = " + accountNumber;
        query +=    " AND cd.did_number= " + cliNumber;

进入这两个:

        int count2 = wrapper.getCreate().update(CUSTOMER_DID)
                        .set(CUSTOMER_DID.IS_CLI_NUMBER, Byte.parseByte("1"))
                        .where(CUSTOMER_DID.CUSTOMER_SERVICE_ID.equal(
                                    wrapper.getCreate().select(KNOW_SERVICE.ID)
                                    .from(CUSTOMER_FLAGS, KNOW_SERVICE)
                                    .where(KNOW_SERVICE.ID.equal(CUSTOMER_DID.CUSTOMER_SERVICE_ID))
                                    .and(KNOW_SERVICE.SERVICE_OWNER_ID.equal(CUSTOMER_FLAGS.ACCOUNT_NUMBER))
                                    .and(KNOW_SERVICE.SERVICE_OWNER_ID.equal(accountNumber))
                                    .and(CUSTOMER_DID.DID_NUMBER.equal(cliNumber))
                                ))
                        .execute();

        int count3 = wrapper.getCreate().update(CUSTOMER_FLAGS)
                .set(CUSTOMER_FLAGS.IS_CLI_NUMBER, Byte.parseByte("0"))
                .where(CUSTOMER_FLAGS.ACCOUNT_NUMBER.equal(
                            wrapper.getCreate().select(KNOW_SERVICE.SERVICE_OWNER_ID)
                            .from(CUSTOMER_DID, KNOW_SERVICE)
                            .where(KNOW_SERVICE.ID.equal(CUSTOMER_DID.CUSTOMER_SERVICE_ID))
                            .and(KNOW_SERVICE.SERVICE_OWNER_ID.equal(CUSTOMER_FLAGS.ACCOUNT_NUMBER))
                            .and(KNOW_SERVICE.SERVICE_OWNER_ID.equal(accountNumber))
                            .and(CUSTOMER_DID.DID_NUMBER.equal(cliNumber))
                        ))
                .execute();

我希望有一种更聪明的方法可以使用jooq重构此查询,而不必将其拆分为两个大量查询。

1 个答案:

答案 0 :(得分:4)

原则上,JOIN操作是在org.jooq.Table上指定的。还有一个待处理的功能请求,即添加"加入便利方法"同样也UPDATESELECT#3266

您的原始查询可以在jOOQ中编写:

CustomerDid cd = CUSTOMER_DID.as("cd");
KnowService ks = KNOW_SERVICE.as("ks");
CustomerFlags cf = CUSTOMER_FLAGS.as("cf");

ctx.update(cd.leftJoin(kd)
             .on(ks.ID.eq(cd.CUSTOMER_SERVICE_ID))
             .leftJoin(cf)
             .on(ks.SERVICE_OWNER_ID.eq(cf.ACCOUNT_NUMBER)))
   .set(cd.IS_CLI_NUMBER, 1)
   .set(cf.IS_CLI_NUMBER, "0")
   .where(ks.SERVICE_OWNER_ID.eq(accountNumber))
   .and(cd.DID_NUMBER.eq(cliNumber))
   .execute();