我有两个要插入行的表。通过外键连接。我正在使用Java 8 Postgres 9.5.4。
我尝试使用RETURNING子句,该子句在pgAdmin(值> = 1)中有效,但在使用我的Java应用程序运行时有效。然后将该值设置为-1并引发错误。
这是我对pgAdmin的工作查询,
INSERT INTO counting_table (count1, cout2)
VALUES (3, 2) RETURNING id
这将在pgAdmin中返回正确的值,但是当输入为时,
@SqlUpdate("INSERT INTO counting_table (count1, count2) " +
"VALUES (:count1, :count2) " +
"RETURNING id")
int insertCountingTable(@Bind("count1") int count1,
@Bind("count2")int count2);
@CreateSqlObject
@Override
public void add(Person person, int count1, int count2)
{
try(Handle handle = jdbi.open())
{
PersonDao personDao = handle.attach(PersonDao.class);
int id = personDao.insertCountingTable(count1, count2);
personDao.insertPerson(person.getPersonId(),
person.getName(), id);
}
}
当行
int id = personDao.insertCountingTable(count1, count2);
执行,将id设置为-1,但该值应> = 1, 还检查数据库,我看到该行已成功插入。
答案 0 :(得分:1)
我无法使RETURNING
子句按照我想要的方式工作,但是使用查询上方的@GetGeneratedKeys
注释并删除了RETURNING
行,我能够实现预期的结果。
我的代码现在看起来像这样
@SqlUpdate("INSERT INTO counting_table (count1, count2) " +
"VALUES (:count1, :count2)")
@GetGeneratedKeys
int insertCountingTable(@Bind("count1") int count1,
@Bind("count2")int count2);