问题
I want to select all fields from one table, fetch into a record of another table, and insert the record into that table. However, I am getting an error saying that the values are null. Here is the relevant piece of code:
// Fetch
PersonDeactivatedRecord person = getContext().selectFrom(PERSON)
.where(PERSON.ID.eq(id))
.fetchOneInto(PersonDeactivatedRecord.class);
// Insert
person.setDeactivatedOn(new Timestamp(System.currentTimeMillis()));
getContext().insertInto(PERSON_DEACTIVATED)
.set(person)
.execute();
The person_deactivated
table is a copy of person
table plus one more column (deactivated_on). The error I'm getting is this:
org.jooq.exception.DataAccessException: SQL [insert into "xxx"."person_deactivated" ("deactivated_on") values (cast(? as timestamp))]; ERROR: null value in column "id" violates not-null constraint
Detail: Failing row contains (null, null, null, null, null, null, null, null, null, ...)
Note that when I debug this code I see that person
object is fully populated as expected. Any idea what I'm missing here?
回答1:
The InsertSetStep.set(Record) method will not insert the entire person
record into the target table, but consider only those fields whose value is "changed". See the Javadoc:
This is the same as calling set(Map) with the argument record treated as a
Map<Field<?>, Object>
, except that the Record.changed() flags are taken into consideration in order to update only changed values.
So, you have several possibilities to fix this issue (there are more than the ones I list here, of course):
1. Set all changed flags to true
This will be the simplest fix:
// Insert
person.setDeactivatedOn(new Timestamp(System.currentTimeMillis()));
person.changed(true); // Sets all flags to true
getContext().insertInto(PERSON_DEACTIVATED)
.set(person)
.execute();
2. Write a single query
The advantage of this solution is that you have only a single query, which means:
- A single server roundtrip (less latency)
- Better locking semantics (the database knows what you're doing, so there are less chances of race conditions)
So, you could write:
getContext()
.insertInto(PERSON_DEACTIVATED)
.columns(PERSON_DEACTIVATED.fields())
.select(
select(Arrays
.stream(PERSON_DEACTIVATED.fields())
.map(f -> f.equals(PERSON_DEACTIVATED.DEACTIVATED_ON)
? currentTimestamp()
: PERSON.field(f))
.collect(Collectors.toList()))
.from(PERSON)
.where(PERSON.ID.eq(id))
)
.execute();
As always, this answer assumes you have the following static import in your code:
import static org.jooq.impl.DSL.*;
The above query will insert all columns from PERSON
into PERSON_DEACTIVATED
, except the DEACTIVATED_ON
column will be replaced by the current timestamp.
来源:https://stackoverflow.com/questions/41618843/jooq-fetch-record-from-table-and-insert-it-into-another-table