Dimitri Dewaele
Dimitri Dewaele

Reputation: 10659

JPA entity id - primitive or object type (long or Long)

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

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() {
    }

Upvotes: 46

Views: 37017

Answers (3)

i3ensays
i3ensays

Reputation: 2914

Use a String type for your entity id. Numeric types are intended for sequences or performing mathematical comparison and computations. If using a guid/uuid generator for id, you'll likely need to allow for non-numeric characters anyway (e.g. hyphens).

Upvotes: 1

V G
V G

Reputation: 19002

I consider having Long is better, as it 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(d) 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.

Upvotes: 44

wallenborn
wallenborn

Reputation: 4273

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.

Upvotes: 11

Related Questions