使用JPQL删除elementcollection时的约束错误

时间:2016-11-22 12:13:05

标签: hibernate jpa

JPQL:

delete from Session where deviceId=:deviceId and username=:username

错误:

org.hibernate.engine.jdbc.spi.SqlExceptionHelper: ERROR: update or delete on table "edge_session" violates foreign key constraint "fkh7j6o58rfwfumainodrxptobt" on table "session_contactmethods"

会话班:

@Entity
@Table(name="EDGE_SESSION")
public class Session {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ElementCollection(targetClass=ContactMethod.class)
    @Enumerated(EnumType.STRING)
    private Set<ContactMethod> contactMethods;

...
}

我应该将特定的CascadeTypes添加到contactMethods字段吗?因为外表有一个枚举,我假设删除应该没有发生,因为我希望保留枚举列表?

编辑:看起来它创建的session_contactmethods表不仅仅是枚举值,而是与会话的连接键。

# \d session_contactmethods
        Table "public.session_contactmethods"
     Column     |          Type          | Modifiers
----------------+------------------------+-----------
 session_id     | bigint                 | not null
 contactmethods | character varying(255) |
Foreign-key constraints:
    "fkh7j6o58rfwfumainodrxptobt" FOREIGN KEY (session_id) REFERENCES edge_session(id)

# select * from session_contactmethods;
 session_id | contactmethods
------------+----------------
          1 | EMAIL
          1 | TELEPHONE
          2 | TELEPHONE
          2 | EMAIL
(4 rows)

1 个答案:

答案 0 :(得分:2)

有两种方法可以删除JPA中的对象。

  1. 使用EntityManager.remove(...)。这将根据需要级联 取决于级联设置。
  2. 使用Bulk Delete查询。这不会级联,你基本上是说“相信我,我知道我在做什么”
  3. 您选择了后者,它会按照您的指示尝试执行操作,但由于显而易见的原因存在连接数据而失败。使用第一个选项,或首先从受影响的会话对象中删除相关对象

相关问题