【问题标题】:Postgres unique constraint not deferrable in hibernatePostgres唯一约束在休眠中不可延迟
【发布时间】:2014-03-17 11:27:03
【问题描述】:

我在 PostgreSQL 数据库中创建了一个唯一约束并将其设置为deferrable initially deferred

例如,我在列 order_num 上有唯一键,我在数据库中有两行,如下所示:

id      order_num           description
1               1           'something no 1'
2               2           'something no 2'

当我尝试在数据库上执行此脚本时(即使按照这种不合逻辑的顺序),它运行良好:

begin transaction;
    insert into some_table(id, order_num, description) values(3, 2, 'something no 3');
    delete from some_table where id = 2;
end transaction;

但是当我尝试从应用程序中执行此操作时(即使按照逻辑顺序,先删除,然后插入)它说duplicate key value violates unique constraint

有人知道休眠有什么问题吗?如何设置可延期?

编辑: 好的,唯一约束由id_ri_contentid_structure_table_columnelement_order 组成。

当我从 PG 管理员运行事务时,日志显示如下:

2014-03-17 13:45:15 CET LOG: statement: begin transaction; insert into ri_content_cell(id_ri_content_cell, id_ri_content, id_ri_structure_table_column, element_order, content) values(118, 41, 226, 2, '3'); insert into ri_content_cell(id_ri_content_cell, id_ri_content, id_ri_structure_table_column, element_order, content) values(119, 41, 228, 2, 'Zika'); delete from ri_content_cell where id_ri_content_cell in (120,121); end transaction;

从 java 会话 bean 方法在 hibernate 中运行相同时会产生此错误日志:

2014-03-17 13:54:25 CET LOG: execute : select nextval ('ri_content_cell_seq') 2014-03-17 13:54:25 CET LOG: execute : select nextval ('ri_content_cell_seq') 2014-03-17 13:54:25 CET LOG: execute : insert into ri_content_cell (content, element_order, id_ri_content, id_ri_structure_table_column, id_ri_content_cell) values ($1, $2, $3, $4, $5) 2014-03-17 13:54:25 CET DETAIL: parameters: $1 = '2', $2 = '2', $3 = '41', $4 = '226', $5 = '136' 2014-03-17 13:54:25 CET ERROR: duplicate key value violates unique constraint "uk_ri_content_cell" 2014-03-17 13:54:25 CET DETAIL: Key (id_ri_content, id_ri_structure_table_column, element_order)=(41, 226, 2) already exists.

【问题讨论】:

  • 这是一个 SQLException,对吧?如果它是 SQLException,那么它来自 PostgreSQL,而不是来自 Hibernate。所以要么你有几个事务,要么约束没有真正延迟,或者违反了其他一些约束,或者你没有真正删除行。
  • 我认为这是休眠异常,但是完整的异常名称是:12:09:32,262 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080 -12)SQL 错误:0,SQLState:23505 12:09:32,262 错误 [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-12) 错误:重复键值违反唯一约束“uk_ri_content_cell”
  • 在 PostgreSQL 级别记录整个事务。编辑postgresql.conf 并设置log_statement = 'all' 并确保有一个有用的log_line_prefix。然后从 PostgreSQL 日志中获取整个系列的语句。在连接设置期间看到SET CONSTRAINTS 语句我不会感到惊讶。
  • 发布完整的堆栈跟踪,而不是甚至不包含异常类名称的日志语句。
  • 编辑部分是我写的。

标签: hibernate postgresql unique-constraint


【解决方案1】:

检查 Hibernate 正在使用的数据源的 JTA 是否设置为 TRUE。

【讨论】:

  • 谢谢,我在数据源中设置 jta="true" 后它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 2020-04-19
相关资源
最近更新 更多