Reputation: 1261
Jpa entity generator assigns Integer type to the id fields of my entities. The corresponding attribute/column in my DB is of type serial ( yep postgres
). I would also assign the integer type to my entities id fields. But i have seen usage of Long getId()
on this page. I have also seen this type of type assigning on the geomajas examples. Is there any gotcha when it comes to using Integer
? I mean, yeah you have to be careful with integer that the id is not below 0 but at the same time you also have to make sure that your Long Id is not bigger than 2,147,483,647. So what's deal here?
EDIT: I was making a confusion between Long
and unsigned integer so i guess what i was thinking was "unsigned integer versus Integer
for the id field of java entities" which is nonsense now that my confusion between long and unsigned integer is gone. My bad. Thank you for your answers and comments. I guess if i would have used bigserial jpa entity generator would have used Long too.
Upvotes: 22
Views: 29551
Reputation: 29081
The biggest 'gotcha' is that when you query for an entity, you need to use the EXACT TYPE, or the implementation with throw an exception. And this is a RUNTIME exception.
entityManager.find(MyClass.class, intVal); // fails if type is long
entityManager.find(MyClass.class, longVal); // fails if type is integer
I make the case that for maintainability, consistency among your entities is as important as any memory considerations.
To further this argument, consider that the 'size' does not effect the packets to/from the database.
Upvotes: 2
Reputation: 23105
Jpa entity generator assigns Integer type to the id fields of my entities
You set the type of the id field, the JPA generator fills it with unique values. You are free to use Integer or Long.
Is there any gotcha when it comes to using Integer?
Not really, the only difference between Integer & Long is the number of bits (64 v 32) and permissable range:
Integer: -2,147,483,648 to 2,147,483,647
Long: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
The generator will assign values to the Id field. You can control the initial generated value: for @SequenceGenerator and @TableGenerator, set the initialValue attribute; for Identity generator, modify database DDL definition for the Identity column.
Simply determine (maximum number of Ids generated per week by your app) x (maximum number of weeks your app can be "live"). If the result is less than, say, 1,500,000,000 (giving a safety margin), feel free to use Integer; otherwise use Long.
Upvotes: 18
Reputation: 316
Long
has a much bigger capacity than Integer
data type, so if you are not sure what length your data is going to be, its better to be using Long
type data...
On the other hand, since Long
has a bigger capacity it uses extra space and if you are sure that your data will not be bigger than the Integer
data type then using Long
just makes your code inefficient
Upvotes: 30