pom.xml에 라이브러리 추가
<dependencies>
<!-- Spring Boot JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- JPA 하이버네이트-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.10.Final</version>
</dependency>
<!-- H2 데이터베이스 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
</dependency>
</dependencies>
- H2: 인메모리 DB
테이블 매핑
@Entity(name = "member")
public class Member{
@Id
private Long id;
private String name;
@Builder
public Member(String name){
this.name = name;
}
}
Member | |
(PK) bigint | id |
varchar | name |
- @Entity: JPA가 관리하는 클래스
> name: 속성 지정, 사용할 엔티티 이름 지정
- @Id: 데이터베이스 PK와 매칭
JPA Repository
@Repository
public interface SpringDataJpaRepository extends SpringDataJpaRepository<T, Long>{
// 이름으로 조회
List<T> findListByName(String name);
// 직접 쿼리 설정
@Query(value = "select c from Table c where c.name = name")
List<T> findTableListByName(String name);
...
}
JPA CRUD
public class JPATest {
@Autowired
SchoolRepository schoolRepository;
@Test
public void Insert() {
School school = new School();
school.setName("청아예술 고등학교");
school.setRegion("서울");
school.setRanking(1);
schoolRepository.save(school); // Insert
List<School> schools = schoolRepository.findAll(); // Select
for(int i=0; i<schools.size(); i++) {
schools.get(i).setRegion("경기");
schoolRepository.save(schools.get(i)); // Update
}
schoolRepository.deleteById(1); // Delete
// schoolRepository.deleteAll(); // Delete All
}
}
'IT > 개발' 카테고리의 다른 글
[DB] SELECT ~ FOR UPDATE (0) | 2021.11.05 |
---|---|
[Spring] SpringBoot + Kafka 사용 방법 (0) | 2021.10.29 |
[Spring] JPA란 (0) | 2021.10.29 |
[Spring] Spring Cloud 개념 및 핵심 컴포넌트 (0) | 2021.10.01 |
[SpringBoot] Transaction 사용하기 (0) | 2021.09.24 |