Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jOOQ insert query with returning generated keys

Tags:

java

sql

mysql

jooq

I installed jOOQ into eclipse, generated classes for my mySQL, but I still have problems to write also some basic queries.

I tried to compose insert query with returning of generated keys, but compiler throws error

Table: tblCategory Columns: category_id, parent_id, name, rem, uipos

Result<TblcategoryRecord> result= create.insertInto(Tblcategory.TBLCATEGORY, 
    Tblcategory.PARENT_ID, Tblcategory.NAME, Tblcategory.REM, Tblcategory.UIPOS)
        .values(node.getParentid())
        .values(node.getName())
        .values(node.getRem())
        .values(node.getUipos())
        .returning(Tblcategory.CATEGORY_ID)
        .fetch();

tried also other differnt ways how to do it right way?

thanks charis

like image 849
Charis997 Avatar asked Nov 14 '11 20:11

Charis997


1 Answers

The syntax you're using is for inserting multiple records. This is going to insert 4 records, each with one field.

.values(node.getParentid())
.values(node.getName())
.values(node.getRem())
.values(node.getUipos())

But you declared 4 fields, so that's not going to work:

create.insertInto(Tblcategory.TBLCATEGORY, 
  Tblcategory.PARENT_ID, Tblcategory.NAME, Tblcategory.REM, Tblcategory.UIPOS)

What you probably want to do is this:

Result<TblcategoryRecord> result = create
  .insertInto(Tblcategory.TBLCATEGORY, 
    Tblcategory.PARENT_ID, Tblcategory.NAME, Tblcategory.REM, Tblcategory.UIPOS)
  .values(node.getParentid(), node.getName(), node.getRem(), node.getUipos())
  .returning(Tblcategory.CATEGORY_ID)
  .fetch();

Or alternatively:

Result<TblcategoryRecord> result = create
  .insertInto(Tblcategory.TBLCATEGORY) 
  .set(Tblcategory.PARENT_ID, node.getParentid())
  .set(Tblcategory.NAME, node.getName())
  .set(Tblcategory.REM, node.getRem())
  .set(Tblcategory.UIPOS, node.getUipos())
  .returning(Tblcategory.CATEGORY_ID)
  .fetch();

Probably, you're even better off by using

TblcategoryRecord result =
  // [...]
  .fetchOne();

For more details, consider the manual:

http://www.jooq.org/doc/2.6/manual/sql-building/sql-statements/insert-statement/

Or the Javadoc for creating INSERT statements that return values:

http://www.jooq.org/javadoc/latest/org/jooq/InsertReturningStep.html

like image 71
Lukas Eder Avatar answered Oct 20 '22 01:10

Lukas Eder