我有一个 Postgresql
数据库,我正在我的应用程序中使用 JOOQ
。我需要在需要运算符 ->
的地方实现查询。我将运算符用于 select
和 left join
。看看下面:
select coalesce(u.name, data->'username') as username, user_location, user_time
from log
left join users u on (data->'username') is not null and (data->'username') = u.username
where ((data->'code') is null or (data->'code') <> 'no')
实现这个案例的最佳方式是什么?我找到了这个 link但我认为仅仅实现它就太复杂了,不是吗?
最佳答案
如果 jOOQ(还)不支持某些东西,你总是可以求助于使用 plain SQL API .在您的情况下,您可以编写如下实用程序:
public static Field<String> jsonAttr(Field<?> json, String attrName) {
return DSL.field("{0}->{1}", String.class, json, DSL.inline(attrName));
}
请注意 DSL.inline()
会将您的字符串文字转义为 prevent SQL injection .使用普通 SQL API 时始终小心这种可能性
您现在可以像这样使用上面的内容:
// Assuming this static import
import static org.jooq.impl.DSL.*;
// Aliasing
Users u = USERS.as("u");
// You didn't qualify all your columns, so I'm assuming DATA is in LOG
DSL.using(configuration)
.select(
coalesce(u.NAME, jsonAttr(LOG.DATA, "username")).as("username"),
u.USER_LOCATION,
u.USER_TIME)
.from(LOG)
.leftJoin(u)
.on(jsonAttr(LOG.DATA, "username").isNotNull())
.and(jsonAttr(LOG.DATA, "username").eq(u.USERNAME))
.where(jsonAttr(LOG.DATA, "code").isNull())
.or(jsonAttr(LOG.DATA, "code").ne("no"))
.fetch();
关于java - 如何使用 ->(箭头)运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43803130/