Spring Boot3 & Spring Framework 6 강의 ::Section.6 | JDBC, JPA, Spring JPA

suragryen·2024년 2월 26일
0

Udemy-Spring

목록 보기
10/25

자바 어플리케이션에서 데이터베이스와 상호 작용하는 기술인 JDBC(Java Database Connectivity)와 JPA(Java Persistence API)에 차이점에 대해 알아보자. 🧑🏻‍🏫

1. JDBC

@Repository
public class CourseJdbcRepository {
	
	@Autowired
	private JdbcTemplate springJdbcTemplate;
	
	
	
	private static String INSERT_QUERY = 
			"""
				insert into course(id, name, author)
				values (?, ?, ?);
				
			""";
	
	
	private static String DELETE_QUERY = 
			"""
				delete from course
				where id = ?
				
			""";
	
	private static String SELECT_QUERY = 
			"""
				select * from course
				where id = ?
				
			""";
	
	public void insert(Course course) {
		springJdbcTemplate.update(INSERT_QUERY, 
				course.getId(), course.getName(), course.getAuthor());
	}
	
	public void delete(long id) {
		springJdbcTemplate.update(INSERT_QUERY, id);
	}
	
	public Course findById(long id) {
		return springJdbcTemplate.queryForObject(SELECT_QUERY, new BeanPropertyRowMapper<>(Course.class), id);
	}
	

}

쿼리 실행

@Component
public class CourseCommandLineRunner implements CommandLineRunner{
	
	@Autowired
	private CourseJdbcRepository repository;
	

	
	@Override
	public void run(String... args) throws Exception {
		
		repository.insert(new Course(1, "Learn JPA Now", "in28min"));
		repository.insert(new Course(1, "Learn 메롱 Now", "in28min"));
		repository.insert(new Course(1, "Learn 메론 Now", "in28min"));
		
		//repository.delete(1);
		
	}
  • repository를 autowired해주고 쿼리를 실행한다.
    -> 직접 쿼리문을 입력하는 방식.

2. JPA(ORM)


@Repository
@Transactional//클래스의 각 메서드가 트랜잭션 컨텍스트 내에서 실행되도록 보장합니다. 즉, 메서드 중 하나가 실패하면 데이터 일관성을 유지하기 위해 트랜잭션이 롤백됩니다.
public class CourseJpaRepository {
	
	@PersistenceContext //Autowired  대신에 더 구체적인 어노테이션 사용  
	private EntityManager entityManager;//JPA에서 엔티티 관리를 담당하는 핵심 클래스 중 하나이며, 데이터베이스와의 상호 작용을 처리합니다.
	
	public void insert(Course course) {
		entityManager.merge(course);
	}
	
	public Course findById(long id) {
		return entityManager.find(Course.class, id);
	}
	
	public void deleteById(long id) {
		Course course = entityManager.find(Course.class, id);
		entityManager.remove(course);
	}
}
  • JDBC는 SQL문을 작성하는 반면 JPA는 어노테이션과 EntityManager로 SQL문을 대신한다(ORM) 또한 EntityManager는 @Autowired가 아닌 @PersistenceContext와 짝꿍으로 쓰임

ORM 이란?

ORM (Object Relational Mapping)
DB의 데이터를 객체로 매핑시켜 데이터를 접근할 수 있는 것이다.
ORM을 사용하면 SQL을 작성하지 않고도 메소드를 사용해 데이터를 조작할 수 있다. JPA, Hibernate 등이 해당.

쿼리 실행

package com.in28minnutes.springboot.learnjpaandhibernate.course.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.in28minnutes.springboot.learnjpaandhibernate.course.Course;
import com.in28minnutes.springboot.learnjpaandhibernate.course.springdatajpa.CourseSpringDataJpaRepository;

@Component
public class CourseCommandLineRunner implements CommandLineRunner{
	
	//@Autowired
	//private CourseJdbcRepository repository;
	
	//@Autowired
	//private CourseJpaRepository repository;
	
	@Autowired
	private CourseSpringDataJpaRepository repository;
	
	@Override
	public void run(String... args) throws Exception {
		//CourseJpaRepository

		repository.insert(new Course(1, "Learn JPA Now", "in28min"));
		repository.insert(new Course(1, "Learn 메롱 Now", "in28min"));
		repository.insert(new Course(1, "Learn 메론 Now", "in28min"));
		
		repository.deleteById(1);
		
		repository.findById(1);
		
		
		
		
	}

}

3. Spring JPA(ORM)

import org.springframework.data.jpa.repository.JpaRepository;

import com.in28minnutes.springboot.learnjpaandhibernate.course.Course;

public interface CourseSpringDataJpaRepository extends JpaRepository<Course, Long>{

	//entityManater 같은걸 사용할 필요 없이 interface를 extends만 시켜줘도 쿼리를 실행시킬 수 있다.  
	//
	
}
  • SpringDataJpaRepository 클래스를 생성하고 JpaRepository를 상속받으면서 엔터티와 ID를 지정해주면 쿼리를 실행할 수 있음.

쿼리실행

package com.in28minnutes.springboot.learnjpaandhibernate.course.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.in28minnutes.springboot.learnjpaandhibernate.course.Course;
import com.in28minnutes.springboot.learnjpaandhibernate.course.springdatajpa.CourseSpringDataJpaRepository;

@Component
public class CourseCommandLineRunner implements CommandLineRunner{
	
	//@Autowired
	//private CourseJdbcRepository repository;
	
	//@Autowired
	//private CourseJpaRepository repository;
	
	@Autowired
	private CourseSpringDataJpaRepository repository;
	
	@Override
	public void run(String... args) throws Exception {
		

		//CourseSpringDataJpaRepository
		repository.save(new Course(1, "Learn JPA Now", "in28min")); //save는 엔터티를 업데이트하거나 인서트 할 때 사용
		repository.save(new Course(1, "Learn 메롱 Now", "in28min"));
		repository.save(new Course(1, "Learn 메론 Now", "in28min"));
		
		repository.deleteById(1l);
		
		System.out.println(repository.findById(2l));
		System.out.println(repository.findById(2l));
		
		
	}

}
  • save는 쿼리를 인서트하거나 업데이트할때 쓰인다.
profile
블로그 이사중 ☃︎

0개의 댓글

관련 채용 정보