简体   繁体   中英

How to build a condition based on a composite data type with jOOQ?

In my view I have a column that refers to another table as its data type:

CREATE VIEW my_view AS
SELECT c.*, CAST(p.* AS parent) AS entity_parent
FROM entity_child c
LEFT JOIN parent p ON c.parent_id = p.id
GROUP BY c.id, p.id;

I need to query the view based on a value of the entity/parent value. With PostgreSQL it looks like:

SELECT *
FROM my_view
WHERE (entity_parent).secret_value = 42;

jOOQ nows the correct data type of entity_parent (ParentRecord), but I failed to translate my query.

Has anyone an idea?

The jOOQ API currently doesn't allow for generating UDT element dereferencing expressions out of the box. The relevant feature request is this: https://github.com/jOOQ/jOOQ/issues/228

However, as always, you can easily work around such a limitation in the jOOQ API by using the plain SQL templating API: https://www.jooq.org/doc/latest/manual/sql-building/plain-sql-templating

public static <T, U extends UDTRecord> Field<T> dereference(
    Field<? extends U> parent, 
    UDTField<U, T> child
) {
    return DSL.field("({0}).{1}", child.getDataType(), parent, child.getUnqualifiedName());
}

And then, use it as follows:

ctx.selectFrom(MY_VIEW)
   .where(dereference(MY_VIEW.ENTITY_PARENT, Parent.SECRET_VALUE).eq(42))
   .fetch();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM