我正在使用 Hibernate 和 MySql。
我有 2 个表:
User: id, name, type
City: id, name, type
type: id, name
其中 user.type 具有指向 user_type.id 的外键。以及城市。
我想在删除 user_type 表中的行之前,检查任何表中的任何行是否与它相关。
例如,我的列已映射:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "type_id")
我该怎么做?
最佳答案
你说
I have around 100 tables like User and City mapped to this value
好的。 Hibernate with JPA 书说
You may have removed all other references manually
这意味着您应该手动查询任何相关表。但它表示,如果其他实体引用类型,数据库约束会防止任何不一致,并且您会看到外键约束异常。我认为这是检查所需内容的最佳方式。否则,您应该手动查询任何相关表。
try {
userType = (Type) session.load(Type.class, id);
session.delete(userType);
/**
* or JDBCException
* e.getCause()
* e.getErrorCode() - vendor-specific
*/
} catch (HibernateException e) {
// checkout Exception right here e.getCause();
}
Hibernate 抛出的所有异常都是致命的。这意味着您必须回滚数据库事务并关闭当前 session 。所以你可能想打开一个新 session 。
关于java - 如何检查任何对象是否与具有外键约束的表中的行相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3433988/