【发布时间】:2021-01-23 08:09:27
【问题描述】:
我的数据库中有三个表,SUBSCRIPTION、USER_ID,以及一个名为 SUBSCRIPTION_USER_ID 的关联表。
我的策略是使用JOOQ批处理三个查询,第一个在行上插入SUBSCRIPTION,第二个查询在USER_ID中插入多行,最后,我需要插入关联ID进入SUBSCRIPTION_USER_ID,所以我做了以下操作:
InsertValuesStep2 insertUserIds = insertInto(
USER_ID, USER_ID.USER_ID_TYPE, USER_ID.USER_ID_VALUE);
for (String userId : subscriptionDTO.getUserId())
insertUserIds = insertUserIds.values(getValue(0, userId), getValue(1, userId));
InsertReturningStep insertReturningUserIds = insertUserIds.onConflictDoNothing();
InsertResultStep insertReturningSubscription = insertInto(SUBSCRIPTION)
.set(SUBSCRIPTION.CHANNEL_ID, subscriptionDTO.getChannel())
.set(SUBSCRIPTION.SENDER_ID, subscriptionDTO.getSenderId())
.set(SUBSCRIPTION.CATEGORY_ID, subscriptionDTO.getCategory())
.set(SUBSCRIPTION.TOKEN, subscriptionDTO.getToken())
.onConflictDoNothing()
.returningResult(SUBSCRIPTION.ID);
不幸的是,为了向关联表中插入值,我尝试了很多方法但对我没有任何作用,最后,我尝试使用 select 在 SUBSCRIPTION_USER_IDusing 中插入值但它不起作用:
InsertValuesStep insertValuesSubscriptionUserIds = insertInto(
SUBSCRIPTION_USER_ID,
SUBSCRIPTION_USER_ID.SUBSCRIPTION_ID,
SUBSCRIPTION_USER_ID.USER_ID_ID)
.select(select(SUBSCRIPTION.ID, USER_ID.ID)
.from(SUBSCRIPTION)
.innerJoin(USER_ID)
.on(concat(USER_ID.USER_ID_TYPE,
val(CATEGORY_USER_ID_DELIMITER),
USER_ID.USER_ID_VALUE).in(subscriptionDTO.getUserId())
.and(SUBSCRIPTION.SENDER_ID.equal(subscriptionDTO.getSenderId()))
.and(SUBSCRIPTION.CHANNEL_ID.equal(subscriptionDTO.getChannel()))
.and(SUBSCRIPTION.CATEGORY.equal(subscriptionDTO.getCategory()))
.and(SUBSCRIPTION.TOKEN.equal(subscriptionDTO.getToken()))));
我在上面遗漏了什么吗?有没有更好的方法使用 JOOQ 插入多对多关系值或使用查询结果作为其他查询的参数?
【问题讨论】:
标签: java many-to-many jooq