
요약
JPA, MySql 기본 설정을 하고 JPA에서 제공하는 CRUD 메서드를 구경해보자
JPA ( Java Persistence API)
JPA는 MyBatis처럼 SQL과 프로젝트를 연동하는 놈
JPA vs MyBatis

JPA는 JPA만의 고유한 메모리 공간 (콘텍스트 context)가 존재한다.
MyBatis는 SQL이 실행되고 나면 객체가 어떻게 되든 상관이 없는 반면에,
JPA에서 사용하는 객체들은 콘텍스트 내부에서 관리된다. 그래서 객체들이 변경이 되면 DB에 이를 반영하는 방식이다.
JPA는 객체가 계속 유지되고, 필요할때 꺼내서 재사용하는 방식인데, 이때 리스너(Listener)가 객체의 변화를 감지하여 DB에 반영하던가 한다.
사용 기준은 복잡한 쿼리나 제어가 필요할때는 MyBatis, 간단한 매핑 & 객체지향적 접근이 필요할때는 JPA가 더 유리하다!
MySQL workbench
bootex로 새로운 스키마 생성

Administration > Users and Privileges > testuser 선택 > Schema Privileges > Add Entry
> Selected schema : bootex 선택 > 권한 다 주고(Select "All") > Apply

home에서 Setup New Connection

프로젝트 생성
project name : ex2

이대로 실행시키면 오류가 뜬다.
properties에 포트와 datasource추가
spring.application.name=ex2
server.port=8090
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bootex
spring.datasource.username=testuser
spring.datasource.password=test1234
+) 자동으로 필요한 테이블 생성 & JPA 이용 시 필요한 설정
spring.jpa.hibernate.ddl-auto=update //프로그램 실행시 테이블이 없다면 자동으로 테이블 설정
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true
엔티티 클래스 & JpaRepository
src > main > java > ex2 > entity 패키지 생성 > Memo 생성
- @Entity
- 엔티티를 위한 클래스, 해당 클래스의 인스턴스들은 JPA로 관리되는 엔티티 객체임
- @Table
- DB상에서 엔티티 클래스를 어떠한 테이블로 생성할것인지에 대한 정보를 담는다
- @GeneratedValue
- 자동으로 생성되는 번호 사용 ( PK 자동생성 )
- auto increment처럼
- @Column
- 추가적인 필드를 작성할때
@Column(length = 200,nullable = false) private String memoText;
JpaRepository Interface
src > main > java > ex2 > repository 패키지 생성 > MemoRepository 인터페이스 생성
package com.example.ex2.repository;
import com.example.ex2.entity.Memo; //이녀셕의 객체를 자동으로 생성
import org.springframework.data.jpa.repository.JpaRepository;
//인터페이스 선언만으로 자동으로 스프링의 빈(객체)를 생성한다.
public interface MemoRepository extends JpaRepository<Memo, Long> {
}
MemoRepository는 인터페이스 그 자체이고, JpaRepository를 상속 하는것만으로 작업이 다 끝난다.
-> 선언만으로 자동으로 빈이 등록됨.
JpaRepository 메서드
- insert : save
- select : findById
- update : save
- delete : deleteById , delete
- insert, update 모두 save를 이용
- JPA에서 객체를 비교해서 없으면 insert를 하고, 있으면 update를 한다.
- insert, update 모두 save를 이용
save() 메서드 Test : insert
package com.example.ex2.repository;
import com.example.ex2.entity.Memo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.stream.IntStream;
@SpringBootTest
public class Tests {
@Autowired
MemoRepository memoRepository;
@Test
public void test() {
System.out.println(memoRepository.getClass().getName());
}
@Test
public void testInsertDummies() {
IntStream.rangeClosed(1,100).forEach(i -> {
Memo memo = Memo.builder().memoText("Sample "+i).build();
memoRepository.save(memo);
});
}
}
testInsertDummies() 에서 memo 객체를 100개 생성하고 ,save()메서드를 이용해서 객체 100개를 생성했다.
db에 객체가 이미 있다면 update를 했겠지만, 없으니 insert를 실행하여 db에 저장되었다.

findById() 메서드 Test : select
@Test
public void testSelect() {
Long mno = 5L;
Optional<Memo> result = memoRepository.findById(mno);
System.out.println("================");
if(result.isPresent()){
Memo memo = result.get();
System.out.println(memo);
}
}
mno 가 5인 놈을 result에 저장하고, 출력한다.
결과:
Hibernate:
select
m1_0.mno,
m1_0.memo_text
from
tbl_memo m1_0
where
m1_0.mno=?
================
Memo(mno=5, memoText=Sample 5)
save() 메서드 Test : update
//update
@Test
public void testUpdate(){
Memo memo = Memo.builder().mno(1L).memoText("update sample").build();
memoRepository.save(memo);
}
1번놈 memo_text가 update sample 로 바뀜
deleteById() 메서드 Test : delete
//delete
@Test
public void testDelete() {
Long mno = 100L;
memoRepository.deleteById(mno);
}
100번 놈 삭제됨
'Spring Boot' 카테고리의 다른 글
[ Spring Boot ] 스프링MVC & Thymeleaf part.3 (0) | 2024.07.30 |
---|---|
[ Spring Boot ] 스프링MVC & Thymeleaf part.2 (0) | 2024.07.30 |
[ Spring Boot ] 스프링MVC & Thymeleaf part.1 (0) | 2024.07.30 |
[ Spring Boot ] @Query 어노테이션, Querydsl (0) | 2024.07.30 |
[ Spring Boot ] 프로젝트 생성, 테스트 (0) | 2024.07.29 |

요약
JPA, MySql 기본 설정을 하고 JPA에서 제공하는 CRUD 메서드를 구경해보자
JPA ( Java Persistence API)
JPA는 MyBatis처럼 SQL과 프로젝트를 연동하는 놈
JPA vs MyBatis

JPA는 JPA만의 고유한 메모리 공간 (콘텍스트 context)가 존재한다.
MyBatis는 SQL이 실행되고 나면 객체가 어떻게 되든 상관이 없는 반면에,
JPA에서 사용하는 객체들은 콘텍스트 내부에서 관리된다. 그래서 객체들이 변경이 되면 DB에 이를 반영하는 방식이다.
JPA는 객체가 계속 유지되고, 필요할때 꺼내서 재사용하는 방식인데, 이때 리스너(Listener)가 객체의 변화를 감지하여 DB에 반영하던가 한다.
사용 기준은 복잡한 쿼리나 제어가 필요할때는 MyBatis, 간단한 매핑 & 객체지향적 접근이 필요할때는 JPA가 더 유리하다!
MySQL workbench
bootex로 새로운 스키마 생성

Administration > Users and Privileges > testuser 선택 > Schema Privileges > Add Entry
> Selected schema : bootex 선택 > 권한 다 주고(Select "All") > Apply

home에서 Setup New Connection

프로젝트 생성
project name : ex2

이대로 실행시키면 오류가 뜬다.
properties에 포트와 datasource추가
spring.application.name=ex2
server.port=8090
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bootex
spring.datasource.username=testuser
spring.datasource.password=test1234
+) 자동으로 필요한 테이블 생성 & JPA 이용 시 필요한 설정
spring.jpa.hibernate.ddl-auto=update //프로그램 실행시 테이블이 없다면 자동으로 테이블 설정
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true
엔티티 클래스 & JpaRepository
src > main > java > ex2 > entity 패키지 생성 > Memo 생성
- @Entity
- 엔티티를 위한 클래스, 해당 클래스의 인스턴스들은 JPA로 관리되는 엔티티 객체임
- @Table
- DB상에서 엔티티 클래스를 어떠한 테이블로 생성할것인지에 대한 정보를 담는다
- @GeneratedValue
- 자동으로 생성되는 번호 사용 ( PK 자동생성 )
- auto increment처럼
- @Column
- 추가적인 필드를 작성할때
@Column(length = 200,nullable = false) private String memoText;
JpaRepository Interface
src > main > java > ex2 > repository 패키지 생성 > MemoRepository 인터페이스 생성
package com.example.ex2.repository;
import com.example.ex2.entity.Memo; //이녀셕의 객체를 자동으로 생성
import org.springframework.data.jpa.repository.JpaRepository;
//인터페이스 선언만으로 자동으로 스프링의 빈(객체)를 생성한다.
public interface MemoRepository extends JpaRepository<Memo, Long> {
}
MemoRepository는 인터페이스 그 자체이고, JpaRepository를 상속 하는것만으로 작업이 다 끝난다.
-> 선언만으로 자동으로 빈이 등록됨.
JpaRepository 메서드
- insert : save
- select : findById
- update : save
- delete : deleteById , delete
- insert, update 모두 save를 이용
- JPA에서 객체를 비교해서 없으면 insert를 하고, 있으면 update를 한다.
- insert, update 모두 save를 이용
save() 메서드 Test : insert
package com.example.ex2.repository;
import com.example.ex2.entity.Memo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.stream.IntStream;
@SpringBootTest
public class Tests {
@Autowired
MemoRepository memoRepository;
@Test
public void test() {
System.out.println(memoRepository.getClass().getName());
}
@Test
public void testInsertDummies() {
IntStream.rangeClosed(1,100).forEach(i -> {
Memo memo = Memo.builder().memoText("Sample "+i).build();
memoRepository.save(memo);
});
}
}
testInsertDummies() 에서 memo 객체를 100개 생성하고 ,save()메서드를 이용해서 객체 100개를 생성했다.
db에 객체가 이미 있다면 update를 했겠지만, 없으니 insert를 실행하여 db에 저장되었다.

findById() 메서드 Test : select
@Test
public void testSelect() {
Long mno = 5L;
Optional<Memo> result = memoRepository.findById(mno);
System.out.println("================");
if(result.isPresent()){
Memo memo = result.get();
System.out.println(memo);
}
}
mno 가 5인 놈을 result에 저장하고, 출력한다.
결과:
Hibernate:
select
m1_0.mno,
m1_0.memo_text
from
tbl_memo m1_0
where
m1_0.mno=?
================
Memo(mno=5, memoText=Sample 5)
save() 메서드 Test : update
//update
@Test
public void testUpdate(){
Memo memo = Memo.builder().mno(1L).memoText("update sample").build();
memoRepository.save(memo);
}
1번놈 memo_text가 update sample 로 바뀜
deleteById() 메서드 Test : delete
//delete
@Test
public void testDelete() {
Long mno = 100L;
memoRepository.deleteById(mno);
}
100번 놈 삭제됨
'Spring Boot' 카테고리의 다른 글
[ Spring Boot ] 스프링MVC & Thymeleaf part.3 (0) | 2024.07.30 |
---|---|
[ Spring Boot ] 스프링MVC & Thymeleaf part.2 (0) | 2024.07.30 |
[ Spring Boot ] 스프링MVC & Thymeleaf part.1 (0) | 2024.07.30 |
[ Spring Boot ] @Query 어노테이션, Querydsl (0) | 2024.07.30 |
[ Spring Boot ] 프로젝트 생성, 테스트 (0) | 2024.07.29 |