0

在 Hibernate 和 Ehcache 中使用可变 ID 是否安全?另请注意,这hashCode是基于 ID 的。

class Company implements Serializable {
  String code; // PK
  public int hashCode() {
    return code == null ? 17 : code.hashCode();
  }
  public boolean equals(Object o) {
    // Some obvious equals checking for type and field equality
  }
}
4

2 回答 2

3

There is a difference between business key and surrogate key concepts. Usually, ID means an immutable identifier (surrogate key), which has no business meaning. At the database level a corresponding column would be a primary key, so that it could be referenced by foreign keys in other tables to ensure referential integrity. Entity properties that model ID are often of type Long. Its value is assigned once and never changed.

The business key could consists of one or more entity properties (and thus columns), which can be mutable.

The provided in the question snippet suggests that field code (should be private) is a business key. So, it can be changed as required. Although the entity type is missing an ID field.

于 2012-04-18T12:03:22.043 回答
2

这可能不是一个好主意。(这表明您打算使用业务键(代码)作为对象的主键。如果您的流程要求您能够更改或重新分配键,这可能会导致复杂化。)

但是,它是否安全(至少在 Hibernate 的情况下)取决于“代码”字段是如何变异的,然后是变异的。如果在对象持久化后更改其代码,则会破坏内存和数据库中的副本之间的关系,并且会发生不好的事情。

另一个问题是,如果“代码”字段在对象位于HashMapor时发生更改HashSet,则对象或条目可能会丢失。

于 2012-04-18T12:10:14.640 回答