프로그래밍/JPA

SpringBoot JPA (feat. h2 db)

kkwonsy 2019. 7. 3. 15:09


이번 포스팅은 SpringBoot와 JPA를 다루는 방법에 대해 아주 간략하게 작성했다. 




로컬에서 개발환경을 구축하면 H2 DB를 많이들 사용하곤 한다.

H2 DB는 설치형이 아닌 SpringBoot에 Embedded 되어 있기 때문인 듯 하다.

즉, 로컬에 MySQL 등의 설치가 안되어 있어도 프로젝트를 로컬환경에서 실행할 수 있어 외부 미들웨어에 대한 디펜던시를 없애는 장점이 있다.



디펜던시 걸기

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2'


여기서 H2 DB는 일반적으로 웹형태의 콘솔을 사용하기 때문에 불편한 점이 많다. IntelliJ에서 Database Client 기능을 제공해주는데 (유료버전만..) 자세한 내용은 아래의 링크를 참고하자. 

SpringBoot H2 DB 클라이언트로 IntelliJ 사용하기





profiles 

spring:
profiles: local

datasource:
platform: h2
url: jdbc:h2:mem:testdb
username: sa
password:
driver-class-name: org.h2.Driver
jpa:
database-platform: H2
show-sql: true
hibernate:
ddl-auto: create-drop



Entity

@NoArgsConstructor
@ToString
@Getter
@Entity(name = "tb_my_entity")
public class MyEntity extends TimeEntity implements Serializable {


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

@Column(length = 200, nullable = false)
private String title;

@Column(length = 500, nullable = false)
private String content;

@Column(length = 100)
private String someId;

@Builder
public MyEntity(String title, String content, String someId) {
this.title = title;
this.content = content;
this.someId = someId;
}

}


createdDate, modifiedDate에 대해서 LocalDate를 등록했더니 table에 Binary로 등록이 된다.

Date로 등록하는 방법을 찾다가 좋은 블로그 글을 발견했다. 

Spring boot hibernate jpa에서 Auditing 사용 - update, create 시간 자동 변경


TimeEntity abstract class를 생성하고 아래 두 애노테이션을 활용하면 된다. 

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)


그 전에 Application에 @ EnableJpaAuditing 애노테이션을 등록해야 한다.

@EnableJpaAuditing
public class Application {




Repository

public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {

List<MyEntity> findTop10BySomeIdOrderByModifiedDateAsc(String someId);


JpaRepository를 상속하면 기본적인 CRUD 기능들을 사용할 수 있다.

커스텀이 필요하면 위에 기재된대로 Naming 규칙을 지켜주면 된다.