Programming/JAVA
[JAVA] Springboot JPA
신샤인
2022. 1. 9. 14:34
반응형
JPA는 관계형 데이터베이스를 관리를 표현하는 자바 API이다.
javax.persistence 라이브러리 사용한다.
테이블 생성 시퀀스 설정
Student 클래스에 시퀀스를 생성한다.
// student.class 파일 수정
@Entity
@Table
public class Student {
@Id
@SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
...
App 실행 시 로그에 student_sequence를 생성하는 것을 확인할 수 있음
아래 해당 정보는 DB 테이블을 생성함
postgres student db에 접속해보면 테이블이 생성된 것을 확인할 수 있다.
데이터를 저장하는 JPA 레포지토리 생성
Service 클래스에 StudentRepository DI 설정한다.
Service에 있는 DB 조회 관련된 코드들을 Config로 설정함.
StudentRepository.java
package com.js.app.student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long>
{
}
StudentService.java
package com.js.app.student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
//StudentRepository Final 구조체 생성
private final StudentRepository studentRepository;
@Autowired
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public List<Student> getStudents() {
return studentRepository.findAll();
}
}
StudentConfig.java
package com.js.app.student;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 커맨드라인을 이용하여 Postgresql에 해당 데이터 값 Insert
@Configuration
public class StudentConfig {
@Bean
CommandLineRunner commandLineRunner(StudentRepository repository) {
return args -> {
Student mariam = new Student(
"mariam",
"mariam@gmail.com",
LocalDate.of(2000, Month.JANUARY,6),
21);
Student alex = new Student(
"Alex",
"alex@gmail.com",
LocalDate.of(2004, Month.JANUARY,6),
25);
repository.saveAll(
List.of(mariam, alex)
);
};
}
}
App 실행 시 데이터가 Insert 되는 것을 확인할 수 있다.
컬럼으로 쓰지 않는 Transient
@Transient 어노테이션을 사용하면 DB 테이블에는 기록되지 않지만 엔티티 클래스에 등록할 수 있다.
Student.java
@Entity
@Table
public class Student {
...
@Transient
private Integer age;
public Student(Long id, String name, String email, LocalDate dob) {
this.id = id;
this.name = name;
this.email = email;
this.dob = dob;
}
...
public Integer getAge() {
return Period.between(this.dob, LocalDate.now()).getYears();
}
...
}
반응형