webfirmframework for Java Experts
Is it a best practice to always use long type for database table id columns in Java entity class?
First of all we should understand, java entity class is just a
data holder for a row, if the id column of a table is
bigint
or
unsigned int
, we should go for
long
data type for
id
property in entity class. The reason is very simple,
int
in java is signed 32 bit value,
bigint/int
database column type can hold more than 31 bit (eg: mysql) value.
If the id column of a database table is int
(signed 32 bit) type, using
int
type for id property in entity class is enough. However if you
think the database table id column type will change from int
to higher size such as bigint or unsigned int,
it may be better to use
long
for
id
property in entity class to avoid future code refactoring. There
are cases where id type of a database table column will be just int
type which will never be changed in future, eg: id type of gender,
country, state etc.. tables. So it is not a best
practice to blindly declare
long
type for id property in java entity class.
