INSERT .. SELECT with some default values in MySQL with JOOQ

99封情书 提交于 2019-12-24 09:48:55

问题


Lets say I have a table Person(id, fname, lname) and it contains a record (1, 'Michael', 'Bay'). Now I wish to create another record in Person table with the same fname and lname but different id i.e. (453456, 'Michael', 'Bay'). This is the way I would do in plain SQL

INSERT INTO Person(id, fname, lname)
SELECT 453456, Person.fname, Person.lname
FROM Person
WHERE Person.id = 1; 

How can this be done with JOOQ (ideally while retaining JOOQ's code generation and type safety features)?

I am aware that JOOQ provides ability to copy entire records from one table to same or another table with its selectFrom syntax

jooq.insertInto(PERSON)
      .select(selectFrom(PERSON).where(PERSON.ID.eq(1)))
      .execute();

But in my case, there are only certain columns in the record that I need to copy while the rest of the values needed to be set explicitly

Another solution I could think of is the following

jooq.insertInto(PERSON)
      .values(452452)
      .execute();

jooq.update(PERSON)
  .set(row(PERSON.FNAME, PERSON.LNAME),
       select(PERSON.FNAME, PERSON.LNAME)
      .from(PERSON)
      .where(PERSON.ID.eq(1)))
  .where(PERSON.ID.eq(452452))
  .execute();

But it doesn't feel right. I would be grateful if someone could provide any other solution/workaround for this problem.


回答1:


jooq.insertInto(PERSON)
    .columns(PERSON.ID, PERSON.FNAME, PERSON.LNAME)
    .select(select(val(452452), PERSON.FNAME, PERSON.LNAME)
           .from(PERSON)
           .where(PERSON.ID.eq(1)))
    .execute();

As always, this is assuming the following static import:

import static org.jooq.impl.DSL.*;


来源:https://stackoverflow.com/questions/50513519/insert-select-with-some-default-values-in-mysql-with-jooq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!