JPA를 통해 회원의 id(기본키)를 생성하고, username과 password를 저장하는 간단한 예제이다. 코드를 파헤쳐보도록 하자!
JPA가 생소하다면 -> JPA 알아보기
Customer Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Builder
@Entity
@Table(name = "customer")
public class CustomerEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "customer_id")
private Long customer_id;
@Column(name = "customer_username", nullable = false)
private String customer_username;
@Column(name = "customer_password", nullable = false)
private String customer_password;
}
@Getter
Entity의 필드를 조회해야할 경우 Getter는 무조건 필요하다.
생성자 어노테이션
@NoArgsConstructor
기본 생성자를 만들어 준다.
JPA가 기본적으로 기본 생성자를 요구한다. (하지만 @Entity가 기본 생성자를 만들어줘서 안써도 됨)
하지만 영속성을 지키기 위해서는 개발자의 실수를 막기 위해 접근 제한자를 설정하는게 좋다.
이때, @NoArgsConstructor를 사용하여 Protected로 설정할 수 있다.
@NoArgsConstructor(access = AccessLevel.PROTECTED)
JPA가 접근할 수 있는 최고가 Protected라 이렇게 설정한다.
@AllArgsConstructor
전체 필드에 대한 생성자를 만들어준다.
이걸 굳이 쓰는 이유는, JPA에서는 Setter를 쓰지 않기 때문이다.
Setter를 쓰게 되면 개발자의 실수로 인해 영속성을 잃어버릴 수 있다.
이는 매우 큰 문제....!!!
그래서 빌더 패턴이라는 것을 사용하는데, 바로 @Builder 어노테이션을 사용한다.
이때 @Builder에서 전체 필드에 대한 값을 필요로 하기에 생성자가 필요하게 된다.
그러면 @NoArgsConstructor 썼으니까 된거 아닌가?
- Protected로 접근 제한자를 썼기 때문에 에러가 발생한다.
- Builder가 기본 생성자가 없으면 알아서 만들어 쓰는데, @NoArgsConstructor로 만들어진 생성자가 있기 때문에 기존껄 사용하며 문제가 발생한다.
그러면 @AllArgsConstructor만 쓰면 된거 아닌가?
- 그러면 @Entity도 생성자가 존재하면 기본 생성자를 생성을 안해버린다...
결론
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Builder
@Entity
- @NoArgsConstructor를 사용하여 기본 생성자를 생성하며, 영속성을 지키기 위해 Protected 설정을 한다.
- @AllArgsConstructor를 사용하여 전체 필드에 대한 생성자를 생성하여 @Builder를 사용할 수 있게 한다.
- @Entity 선언
JPA 어노테이션
@Entity
객체(클래스)와 테이블을 매핑해준다.
(@Table의 name을 설정하지 않으면 클래스 이름을 기준으로 매핑한다.)
@Table
객체와 매핑할 테이블을 직접 지정한다.
@Table 속성
Name | 매핑할 테이블 이름 (Default -> @Entity 이름 사용) |
Catalog | catalog 기능이 있는 DB에서 catalog를 매핑한다. |
Schema | schema 기능이 있는 DB에서 schema를 매핑한다. |
uniqueConstraints | DDL 생성 시 유니크 제약조건을 만들어준다. 스키마 자동 생성 기능을 사용해서 DDL 구문을 만들때만 사용한다. |
@Id
해당 필드를 기본키(PK)로 지정한다.
@GeneratedValue
기본키 생성 설정을 할 수 있다. 자동 생성 기능이 있다.
@GeneratedValue 속성 알아보기 <- 곧 포스팅 하겠습니다
@Column
객체 필드를 테이블 컬럼에 매핑한다.
@Column 속성
속성 이름 | 기능 | 기본값 |
name | 필드와 매핑할 테이블의 컬럼 이름을 지정한다. | 객체의 필드 이름 |
updateable | 엔티티 수정 시 이 필드도 같이 수정한다. false 옵션은 읽기 전용일 때 사용한다. |
true |
nullable(DDL) | DDL 생성 시 null 값의 허용 여부를 설정한다. false로 설정하면 not null 제약조건이 붙는다. |
true |
unique(DDL) | @Table의 uniqueConstraints와 같으나, 한 컬럼에 간단히 유니크 제약조건을 걸 때 사용한다. | false |
columnDefinition(DDL) | 데이터베이스 컬럼 정보를 직접 줄 수 있다. | 자바 필드의 타입과 DB 방언 설정 정보를 사용해 적절히 생성 |
length(DDL) | 문자 길이 제약조건. String 타입에만 사용한다. | 255 |
precision, scale(DDL) | BigDecimal (or BigInterger) 타입에서 사용. precision : 소수점을 포함한 전체 자리수 scale: 소수의 자리수 |
precision = 0, scale = 0 |
틀린 부분이 있으면 지적해주시면 감사하겠습니다.
Reference
[Spring] JPA의 기본 CRUD를 사용해보자 !
[Spring Boot] TO-DO List 만들기 - 첫 셋팅 편
'Server' 카테고리의 다른 글
[JPA] 기본키 생성 전략 / @GeneratedValue (0) | 2024.08.25 |
---|---|
[JPA] 영속성 컨텍스트 #2 (0) | 2024.08.08 |
[JPA] cannot drop table '' referenced by a foreign key constraint '' on table 오류 해결 (0) | 2024.08.05 |
[JPA] JPA란 / 영속성 컨텍스트 #1 (0) | 2024.08.02 |
[JPA] GenerationType.IDENTITY 오류 / AUTO_INCREMENT (0) | 2024.08.02 |