gpt4 book ai didi

java - 处理 Hibernate 的错误代码?

转载 作者:行者123 更新时间:2023-12-01 11:57:38 24 4
gpt4 key购买 nike

考虑一个假设的User表:

-- postgres, but it could have been any other SQL database
CREATE TABLE User(
id SERIAL PRIMARY KEY,
mail VARCHAR(32) UNIQUE NOT NULL
);

假设我尝试添加具有相同邮件的两个用户:

session.save(new User(1, "xpto@gmail.com"));
session.save(new User(2, "xpto@gmail.com"));

并通过Hibernate执行它。 Hibernate 会抛出一个 ConstraintViolationException:

Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)

...

Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "users_mail_key"
Detail: Key (mail)=(xpto@gmail.com) already exists.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
...

我想知道的是,除了必须手动解析异常的输出文本之外,是否有一些好的方法来收集错误的原因,以便我可以正确解释问题并对问题使用react。

我意识到这实际上可能更多是 Postgres 驱动程序的问题,而不是 Hibernate 的问题,但我现阶段不确定,所以我认为可能适合在 Hibernate 的上下文中询问。

最佳答案

因此,如果您能够从 getSQLState 获取值,则可以处理异常:

“PostgreSQL 服务器发出的所有消息都分配有五个字符的错误代码,这些错误代码遵循 SQL 标准的“SQLSTATE”代码约定。需要知道发生了哪种错误情况的应用程序通常应该测试错误代码,而不是查看在文本错误消息处。”

来自:http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html

23505 = unique_violation

注意:在此链接中还有列表。

关于java - 处理 Hibernate 的错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com