[Spring] long, Long, Long?

최수아·2025년 7월 21일
post-thumbnail

Java로 서버 개발을 공부하다가 얼마 전에 Kotlin을 처음 해봤는데, 헷갈리는 부분이 있었다.

분명 null 값을 허용하려고 Long 타입을 사용했는데, 오류가 발생했다.
Kotlin에서는 null 값을 허용하려면 Long이 아니라 Long? 으로 선언해야 한다고 한다.

Java에서 long과 Long 차이

long

  • 기본형(primitive)
  • null 불가 (기본값 0)
  • 메모리에 실제 값이 저장되는 8byte 정수형

Long

  • 객체형(wrapper)
  • null 허용
  • DB 기본키 등에 주로 사용
private long count;    // null X, 0으로 초기화
private Long id;       // null O, JPA 기본키로 많이 사용

Kotlin에서는?

Kotlin에는 Java처럼 primitive 타입이 따로 없으며, 모든 숫자 타입이 객체형이다.

Long

  • 객체형
  • null 불가

Long?

  • 객체형
  • null 허용
var count: Long = 0      // null X
var id: Long? = null     // null O

Spring + JPA

Java

Java에서는 보통 이렇게 기본키를 선언한다.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

Kotlin

Kotlin에서는 JPA가 id 필드를 null 상태로 초기화해야 하기 때문에,
nullable 타입인 Long?으로 선언해야 한다.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null
profile
백엔드 개발자가 되고 싶은 고등학생입니다.

1개의 댓글

comment-user-thumbnail
2025년 7월 28일

I've been using eurorx24.net for a few months now, and honestly, it's one of the most reliable online pharmacies I’ve come across. The delivery is discreet, the prices are fair, and the product range is exactly what I need. Highly recommend for anyone looking for a trustworthy source in Germany.

답글 달기