Long vs long (Integer vs int, Boolean vs boolean) in Java and Springboot Entity

In java:

long is a primitive, which must have a value. Simple.

Long is an object, so:

  • it can be null (meaning whatever you like, but "unknown" is a common interpretation)
  • it can be passed to a method that accepts an ObjectNumberLong or long parameter (the last one thanks to auto-unboxing)
  • it can be used as a generic parameter type, ie List<Long> is OK, but List<long> is not OK
  • it can be serialized/deserialized via the java serialization mechanism

Always use the simplest thing that works, so if you need any of the features of Long, use Long otherwise use long. The overhead of a Long is surprisingly small, but it is there.



In Springboot Entity:


...

@Entity

@Table(name = "file", indexes = @Index(columnList = "path"))

public class UploadFile extends EntityObject {

    @Id

    @GeneratedValue(generator = "UUID")

    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")

    private String id;

    @NotNull

    private String path;

    private long type1;

    private Long type2;

}


See in database:

SELECT column_name, is_nullable, data_type FROM information_schema.columns WHERE table_name   = 'file';


column_name     | is_nullable | data_type

-------------+----------+---------

 id             | NO         | character varying

 path     | NO         | character varying

 type1     | NO         | bigint

 type2     | YES         | bigint


Comments