If I have two tables with a simple many-to-one relationship:
CREATE TABLE parent (
id BIGINT PRIMARY KEY,
name VARCHAR(255)
)
CREATE TABLE child (
id BIGINT PRIMARY KEY,
name VARCHAR(255),
parent_id BIGINT FOREIGN KEY REFERENCES parent (id)
)
How can I query on the child table and convert the rows corresponding to the parent table to a Java Record easily with Jooq?
var a = dslContext.select(
PARENT.ID,
PARENT.NAME,
DSL.field(DSL.row(
PARENT.child().ID,
PARENT.child().NAME)
.convert(???)) // How can I convert sub-entities like this?
.fetch(Records.mapping(ChildDTO::new)); // This works fine for the top-level
It seems like something along those lines ^ should work, but I haven't been able to find it. Am I on the right track, or is there another approach I should be taking?
I think there's just a problem of reversed relationships here, where child and parent were confused. This should work?
dslContext
.select(
CHILD.ID,
CHILD.NAME,
row(CHILD.parent().ID, CHILD.parent().NAME).mapping(ParentDTO::new))
.from(CHILD)
.fetch(Records.mapping(ChildDTO::new))
THis example is using Row2.mapping(Function2)
, which is just convenience for an ad-hoc converter placed on the Row2
expression, which is a SelectField<Record2<T1, T2>>
(there's no need to wrap it in DSL.field(...)
, explicitly)