简体   繁体   English

实体类是否应始终具有ID字段

[英]Should an entity class always have an ID field

I asked " Is it really worth implementing toString() for entity classes? ". 我问:“ 真的值得为实体类实现toString()吗? ”。 The answer I accepted demonstrated the utility of the toString() method of an entity class writing the "name" or "ID" of the entity (and, I'd say, not much else). 我接受的答案演示了实体类的toString()方法的实用性,该类写了实体的“名称”或“ ID”(我想说的还有很多)。 But that requires that the entity have a "name" or "ID". 但这要求实体具有 “名称”或“ ID”。

So, should an entity class always have an ID field. 因此,实体类应始终具有ID字段。 If it does not naturally have one, should you add one, given that it is useful only for debugging ? 如果它自然不存在,那么应该添加一个,因为它仅对调试有用吗? A private final long , perhaps? 一场private final long ,也许吧? That can be done elegantly and efficiently . 可以优雅而有效地完成

I'm not talking necessarily about database backed classes. 我并不是在谈论数据库支持的类。 Here by an entity I mean a class that has the invariant (for non-null x ) 这里的实体是指具有不变性的类(对于非null x

x.equals(y) == (x == y)

An ID almost invariantly refers to a field that uniquely identifies a persistent record, regardless of whatever else has changed between instances of objects hydrated from that persistent record. ID几乎始终是指唯一标识永久记录的字段,而不管从该永久记录中水化的对象实例之间发生了什么变化。

So, the short answer to your question is, no, a "domain" class does not necessarily have to have an ID field. 因此,对于您的问题的简短回答是,不,“域”类不一定必须具有ID字段。 Most will, as you will almost certainly want to persist your domain, and in that case it is best practice (beats the pants off a compound PK of, say, first name, last name, DOB and SSN), but if you write a class that just holds stuff in memory, perhaps a view helper or a business logic class, don't bother. 大多数人都会这样做,因为您几乎肯定会希望保留您的域,在这种情况下,这是最佳实践(不要打扰姓氏,姓氏,DOB和SSN的复合PK),但是如果您写了一个只是将内容保存在内存中的类,例如视图帮助程序或业务逻辑类,不必理会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM