JPA entity id - long or Long

最后都变了- 提交于 2019-12-09 00:23:05

问题


Should the ID of your Entity be long (primitive type) or Long (object type)?

  • The ID is the primary key of my table and is never 'null' in the database.
  • My co-workers suggest to use an Object Type Long.
  • Hibernate Reverse Engeneering tool generates a primitive type long for id by default.

What to choose? long or Long?

@Entity
@Table(name = "COUNTRY")
public class CountryEntity implements java.io.Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    private long id;
    @Column(name = "NAME")
    private String name;
    @Column(name = "CURRENCY")
    private String currency;
    @Column(name = "PEOPLE")
    private Long people;
    @Column(name = "SIZE")
    private Long size;

    public CountryEntity() {
    }

回答1:


I consider having Long is better, as is more correct to check whether an entity has persistent identity by checking against the null value (in MySQL you can have an ID of value 0). Also some libraries like Spring base on an ID of type Long (by default) in their logic. See this implementation for an example.

The small advantage of the primitive: it takes a bit less space.

PS:Both are correct & supported according to the JPA specification and the answers to this question are somehow opinion-based.




回答2:


I'd prefer Long, for the simple reason that if you let the database generate ids for you (which you should), you can tell that a recently instantiated CountryEntity object is not yet persisted by checking for id==null. If you use long, then id will always have a non-null value (initially 0), which will change upon persisting the entity.




回答3:


I'll probably get flamed for this, but neither. Id fields should not be represented as numeric types in Java unless you plan on performing mathematical computations on them. Use String instead and you won't run into overflow issues when your id exceeds the capacity of Long. Also try serializing a 24 digit Long to JSON and you'll be in trouble.



来源:https://stackoverflow.com/questions/20421735/jpa-entity-id-long-or-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!