본문 바로가기

개발(합니다)/Java&Spring

[spring boot 설정하기-3.2] JPA 설정 및 사용 방법

반응형

DB 연결에 최근 떠오르는 JPA를 설정하는 방법을 포스팅합니다.

3.1에 이어서 포스팅을 이어가지만 3.2 JPA 환경 설정내용만 보셔도 됩니다.

spring-data-jpa 관련 정보는 아래 사이트에서 확인할 수 있습니다.
https://docs.spring.io/spring-data/jpa/docs/2.4.x/reference/html/#reference

www.baeldung.com/spring-data-jpa-query


1. 의존성 추가

    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

2. application.yml 설정

jpa를 위한 설정을 합니다.

# API 호출시, SQL 문을 콘솔에 출력
  jpa:
    show-sql: true
    # DDL 정의시 데이터베이스의 고유 기능을 사용
    # ex) 테이블 생성, 삭제 등
    generate-ddl: true
    database: mysql
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate:
      ddl-auto: update

3. DB에서 스키마 생성

테스트 하기 위한 테이블을 생성합니다.

create table jpa_user (
    num int not null auto_increment,
    name char(50) not null,
    primary key (num)
    );

4. JPA 연동 테스트

패키지 구성은 아래 사진과 같습니다.

기존 설정했던 내용도 패키지별로 모아두었습니다.

4-1. JpaUser 생성

package com.otrodevym.spring.base.common.jpa;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


@Getter
@Setter
@ToString
@Entity
public class JpaUser {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int num;

    private String name;
}

4-2. JapUserService 생성

package com.otrodevym.spring.base.common.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class JapUserService {

    @Autowired
    private JpaUserRepository jpaUserRepository;


    public JpaUser signup(JpaUser jpaUser) {
        JpaUser jpaUserResult = jpaUserRepository.save(jpaUser);
        return jpaUserResult;
    }
}

4-3. JpaUserContoller 생성

package com.otrodevym.spring.base.common.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class JpaUserContoller {

    @Autowired
    private JapUserService japUserService;

    @PostMapping("/signup")
    public JpaUser signup(@RequestBody JpaUser jpaUser) {
        JpaUser jpaUserResult = japUserService.signup(jpaUser);
        return jpaUserResult;
    }

}

4-4. JpaUserRepository 생성

package com.otrodevym.spring.base.common.jpa;

import org.springframework.data.repository.CrudRepository;


public interface JpaUserRepository extends CrudRepository<JpaUser, Long> {

}

4-5. postman Post 전송

localhost:8080/user/signup

{
    "name" : "otro"
}

4-6. 결과 확인

5. CrudRepository 기본 사용방법

CrudRepository를 상속받아 사용하여 기본적인 CRUD를 제공받아서 사용할 수 있습니다.
https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html

Modifier and Type Method and Description
long count() Returns the number of entities available.
void delete(T entity) Deletes a given entity.
void deleteAll() Deletes all entities managed by the repository.
void deleteAll(Iterable<? extends T> entities) Deletes the given entities.
void deleteById(ID id) Deletes the entity with the given id.
boolean existsById(ID id) Returns whether an entity with the given id exists.
Iterable<T> findAll() Returns all instances of the type.
Iterable<T> findAllById(Iterable<ID> ids) Returns all instances of the type T with the given IDs.
Optional<T> findById(ID id) Retrieves an entity by its id.
<S extends T> S save(S entity) Saves a given entity.
<S extends T>Iterable<S> saveAll(Iterable<S> entities) Saves all given entities.

6. JPA 어노테이션 설명

  • @Query : 네이티브 쿼리 사용 가능
  • @Entity: DB의 테이블 설정
  • @Table: DB 테이블의 이름을 명시하며 테이블과 클래스가 같다면 자동 설정
  • @Id: Index primary key를 의미
  • @Column: DB Column을 명시
  • @GeneratedValue: Primary Key의 전략(Strategy)를 설정하며 디폴트 값은 AUTO이다.
    • AUTO : (persistence provider가) 특정 DB에 맞게 자동 선택
    • IDENTITY : DB의 identity 컬럼 참조
      • SEQUENCE : DB의 시퀀스 컬럼 참조
    • TABLE : 유일성이 보장된 데이터베이스 테이블 참조

7. JPQL 대비 예제

키워드 예제 JPQL 정보
Distinct findDistinctByLastnameAndFirstname select distinct …​ where x.lastname = ?1 and x.firstname = ?2
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is, Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull, Null findByAge(Is)Null … where x.age is null
IsNotNull, NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection<Age> ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> ages) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstname) = UPPER(?1)
반응형