본문 바로가기
Spring/JPA

[JPA] MyBatis와 동시 사용 (DTO/엔티티 분리)

by J4J 2021. 3. 30.
300x250
반응형

안녕하세요. J4J입니다.

 

이번 포스팅은 DTO/엔티티를 분리하여 JPA와 MyBatis를 동시 사용하는 설정에 대해 적어보는 시간을 가져보려고 합니다.

 

 

 

JPA 관련되어 초기 포스팅을 했던 것처럼 JPA와 MyBatis를 동시 사용하는 프로젝트를 구성해보고자 합니다.

 

JPA가 효율적인 것은 JPA를 사용하고, JPA로 구현을 못하거나 MyBatis가 더 효율적인 것은 MyBatis를 사용할 수 있게끔 하여 보다 효율적인 개발환경이 세팅될 것으로 생각됩니다.

 

이번에는 DTO와 엔티티를 분리하여 설정해보도록 하겠습니다.

 

서로 독립되어 있기 때문에 연관되는 것 없이 각자의 스타일대로 작성해줄 수 있다는 특징이 있습니다.

 

DTO와 엔티티를 통합하여 설정하는 것은 다음 포스팅에서 진행하도록 하겠습니다.

 

 

이번 주제는 도서로 하겠습니다.

 

그리고 현재 작성되는 포스팅은 간단한 테스트를 위한 것이기 때문에 JPA와 MyBatis모두 단순 CRUD만 구현해보도록 하겠습니다.

 

 

반응형

 

 

프로젝트 설정 (공통)

 

[ 1. MySQL에 테이블 생성 ]

 

create table book (
    book_id int auto_increment,
    name varchar(50),
    price int, 
    publisher varchar(50),
    primary key(book_id)
);

 

 

[ 2. pom.xml에 maven 설정 ]

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

	...
    
	<properties>
        <java-version>1.8</java-version>
        <org.springframework-version>5.2.11.RELEASE</org.springframework-version>
        <org.aspectj-version>1.9.6</org.aspectj-version>
        <org.slf4j-version>1.7.30</org.slf4j-version>
	</properties>
    
	<dependencies>
		<!-- DB Dependency -->
		<dependency> <!-- 스프링에서 DB처리를 위한 dependency -->
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<dependency> <!-- MySQL 사용을 위한 dependency -->
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>8.0.22</version>
		</dependency>
		
		<dependency> <!-- 커넥션풀을 위한 dependency -->
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-dbcp2</artifactId>
		    <version>2.8.0</version>
		</dependency>
		
		<dependency> <!-- JPA 사용을 위한 Dependency -->
		    <groupId>org.springframework.data</groupId>
		    <artifactId>spring-data-jpa</artifactId>
		    <version>2.2.5.RELEASE</version>
		</dependency>
		
		<dependency> <!-- JPA 사용을 위한 Dependency -->
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-entitymanager</artifactId>
		    <version>5.4.10.Final</version>
		</dependency>
		
		<dependency> <!-- MyBatis 사용을 위한 dependency -->
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.6</version>
		</dependency>
		
		<dependency> <!-- 스프링에서 MyBatis 사용을 위한 dependency -->
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>2.0.6</version>
		</dependency>
		
		<dependency> <!-- 트랜잭션 처리를 위한 dependency -->
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<!-- Lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<scope>provided</scope>
		</dependency>
		
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
			<scope>test</scope>
		</dependency>   
        
		...
        
	</dependencies>
    
	...
    
</project>

 

 

 

 

[ 3. 자바 설정을 위해 web.xml에서 context-param 파일 변경 ]

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- 자바설정으로 변경 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>com.spring.jpa_mybatis.config.RootContext</param-value>
	</context-param>

	<context-param>
		<param-name>contextClass</param-name>
		<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
	</context-param>
    
	...
    
</web-app>

 

 

[ 4. RootContext 클래스 생성 ]

 

package com.spring.jpa_mybatis.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.spring.jpa_mybatis.repository") // JPA 사용을 위한 패키지 탐색
@MapperScan("com.spring.jpa_mybatis.repository") // MyBatis 사용을 위한 패키지 탐색
public class RootContext {
	
	// DB 정보
	@Bean
	public BasicDataSource dataSource() {
		BasicDataSource datasource = new BasicDataSource();
		datasource.setDriverClassName("com.mysql.cj.jdbc.Driver");
		datasource.setUrl("jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC");
		datasource.setUsername("root");
		datasource.setPassword("root");
		
		return datasource;
	}
	
	// jpa 설정
	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
		entityManagerFactory.setDataSource(dataSource());
		entityManagerFactory.setPersistenceUnitName("jpa-mysql"); // persistence.xml의 설정 정의된 이름
		entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
		
		return entityManagerFactory;
	}
	
	// mybatis 사용을 위한 sessionFactory bean 등록
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource());
		sqlSessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml")); // mybatis 설정파일 등록
		return sqlSessionFactory;
	}
   
	// mybatis 사용을 위한 sqlSession bean 등록
	@Bean
	public SqlSessionTemplate sqlSession(SqlSessionFactoryBean sqlsessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlsessionFactory.getObject());
	}
	
	// transactional 설정
	@Bean
	public PlatformTransactionManager transactionManager() throws Exception {
		// MyBatis transactional
		DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
		dataSourceTransactionManager.setDataSource(dataSource());
		
		// JPA transactional
		JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
		jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
		
		// Chained transaction manager (MyBatis X JPA)
		ChainedTransactionManager transactionManager = new ChainedTransactionManager(jpaTransactionManager, dataSourceTransactionManager);
		return transactionManager;
	}
}

 

 

 

 

프로젝트 설정 (JPA)

 

[ 1. JPA 사용을 위한 persisten.xml파일 생성 (src/main/resources/META-INF/persistence.xml) ]

 

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
	xmlns="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="jpa-mysql"> <!-- 이름 -->
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <!-- DB고유 기능 사용 -->
			<property name="hibernate.show_sql" value="true" /> <!-- 콘솔창에 실행되는 SQL문 출력 -->
			<property name="hibernate.format_sql" value="true" /> <!-- SQL출력시 보기 쉽게 정렬 -->
			<property name="hibernate.use_sql_comments" value="true" /> <!-- SQL출력 시 주석도 같이 출력 -->
			<property name="hibernate.id.new_generator_mappings" value="true" /> <!-- JPA표준에 맞춘 새로운 키 생성 전략 설정 -->
		</properties>
	</persistence-unit>
</persistence>

 

 

[ 2. 엔티티 클래스 생성 ]

 

package com.spring.jpa_mybatis.entity;

import java.io.Serializable;

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

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "book")
public class BookEntity implements Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "book_id")
	private int id;
	
	private String name;
	private int price;
	private String publisher;
}

 

 

[ 3. JpaRepository 생성 ]

 

package com.spring.jpa_mybatis.repository;

import java.util.List;

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

import com.spring.jpa_mybatis.entity.BookEntity;

public interface BookJpaRepository extends JpaRepository<BookEntity, Integer>{
	
	public List<BookEntity> findByName(String name); // 이름으로 조회
}

 

 

 

 

프로젝트 설정 (MyBatis)

 

[ 1. MyBatis 설정파일 생성 (src/main/resources/mybatis-config.xml) ]

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 카멜케이스 적용 -->
	</settings>

	<typeAliases>
		<typeAlias type="com.spring.jpa_mybatis.dto.BookDto" alias="book"/> <!-- DTO클래스 alias 등록 -->
	</typeAliases>
	
	<mappers>
		<mapper resource="mapper/bookmapper.xml" /> <!-- 매퍼 등록 -->
	</mappers>
</configuration>

 

 

[ 2. bookmapper 생성 (src/main/resources/mapper/bookmapper.xml) ]

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.spring.jpa_mybatis.repository.BookRepository">
	<insert id="insert" parameterType="book">
		insert
		into book (name, price, publisher)
		values (#{name}, #{price}, #{publisher})
	</insert>
	
	<select id="selectAll" resultType="book">
		select book_id, 
			   name,
			   price,
			   publisher
		from book
	</select>
	
	<select id="selectByName" parameterType="string" resultType="book">
		select book_id, 
			   name,
			   price,
			   publisher
		from book
		where name = #{value}
	</select>
	
	<select id="selectByBookId" parameterType="int" resultType="book">
		select book_id, 
			   name,
			   price,
			   publisher
		from book
		where book_id = #{value}
	</select>
	
	<update id="update" parameterType="book">
		update book
		set name = #{name},
		    price = #{price},
		    publisher = #{publisher}
		where book_id = #{bookId}
	</update>
	
	<delete id="deleteByBookId" parameterType="int">
		delete
		from book
		where book_id = #{value}
	</delete>
</mapper>

 

 

 

[ 3. DTO 클래스 생성 ]

 

package com.spring.jpa_mybatis.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookDto {
	private int bookId;
	private String name;
	private int price;
	private String publisher;
}

 

 

[ 4. Repository 생성 ]

 

package com.spring.jpa_mybatis.repository;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.spring.jpa_mybatis.dto.BookDto;

@Mapper
public interface BookRepository {
	
	public int insert(BookDto book);
	
	public List<BookDto> selectAll();
	
	public List<BookDto> selectByName(String name);
	
	public BookDto selectByBookId(int bookId);
	
	public int update(BookDto book);
	
	public int deleteByBookId(int bookId);
}

 

 

 

 

단위 테스트

 

모든 설정은 끝이 났습니다.

 

마지막으로 MyBatis에서 실행되는 쿼리문을 출력하기 위해 로그 출력 단계를 debug로 변경하겠습니다.

 

테스트를 할 때 사용할 것이니 src/test/resources/log4j.xml파일을 수정해주시면 됩니다.

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	...
    
	<!-- Application Loggers -->
	<logger name="com.spring.jpa_mybatis">
		<level value="debug" /> <!-- 로그 출력 단계 변경 -->
	</logger>
    
	...
    
</log4j:configuration>

 

 

단위 테스트는 CRUD순서대로 테스트를 해보겠습니다.

 

  • CREATE
package com.spring.jpa_mybatis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.spring.jpa_mybatis.config.RootContext;
import com.spring.jpa_mybatis.dto.BookDto;
import com.spring.jpa_mybatis.entity.BookEntity;
import com.spring.jpa_mybatis.repository.BookJpaRepository;
import com.spring.jpa_mybatis.repository.BookRepository;

import lombok.extern.slf4j.Slf4j;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = RootContext.class)
@Slf4j
public class bookTest {
	
	@Autowired
	BookJpaRepository bookJpaRepository; // jpa
	
	@Autowired
	BookRepository bookRepository; // mybatis

	@Test
	public void jpa_mybatis_create() {
		BookEntity bookEntity = new BookEntity();
		bookEntity.setName("자바 ORM 표준 JPA 프로그래밍");
		bookEntity.setPrice(38700);
		bookEntity.setPublisher("에어콘출판");
		
		bookJpaRepository.save(bookEntity);
		
		
		BookDto bookDto = new BookDto();
		bookDto.setName("배워서 바로 쓰는 스프링 프레임워크");
		bookDto.setPrice(45000);
		bookDto.setPublisher("한빛미디어");
		
		bookRepository.insert(bookDto);
		
		
		log.debug(bookJpaRepository.findAll().toString());
		log.debug(bookRepository.selectAll().toString());
	}
}

 

 

실행하면 다음과 같이 데이터가 저장되고 조회되는 것을 확인할 수 있습니다.

 

Hibernate: 
    /* insert com.spring.jpa_mybatis.entity.BookEntity
        */ insert 
        into
            book
            (name, price, publisher) 
        values
            (?, ?, ?)
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.insert - ==>  Preparing: insert into book (name, price, publisher) values (?, ?, ?)
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.insert - ==> Parameters: 배워서 바로 쓰는 스프링 프레임워크(String), 45000(Integer), 한빛미디어(String)
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.insert - <==    Updates: 1
Hibernate: 
    /* select
        generatedAlias0 
    from
        BookEntity as generatedAlias0 */ select
            bookentity0_.book_id as book_id1_0_,
            bookentity0_.name as name2_0_,
            bookentity0_.price as price3_0_,
            bookentity0_.publisher as publishe4_0_ 
        from
            book bookentity0_
DEBUG: com.spring.jpa_mybatis.bookTest - [BookEntity(id=1, name=자바 ORM 표준 JPA 프로그래밍, price=38700, publisher=에어콘출판), BookEntity(id=2, name=배워서 바로 쓰는 스프링 프레임워크, price=45000, publisher=한빛미디어)]
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - ==>  Preparing: select book_id, name, price, publisher from book
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - ==> Parameters: 
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - <==      Total: 2
DEBUG: com.spring.jpa_mybatis.bookTest - [BookDto(bookId=1, name=자바 ORM 표준 JPA 프로그래밍, price=38700, publisher=에어콘출판), BookDto(bookId=2, name=배워서 바로 쓰는 스프링 프레임워크, price=45000, publisher=한빛미디어)]

 

 

 

 

  • READ
package com.spring.jpa_mybatis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.spring.jpa_mybatis.config.RootContext;
import com.spring.jpa_mybatis.repository.BookJpaRepository;
import com.spring.jpa_mybatis.repository.BookRepository;

import lombok.extern.slf4j.Slf4j;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = RootContext.class)
@Slf4j
public class bookTest {
	
	@Autowired
	BookJpaRepository bookJpaRepository; // jpa
	
	@Autowired
	BookRepository bookRepository; // mybatis
	
	@Test
	public void jpa_mybatis_read() {
		log.debug(bookJpaRepository.findByName("자바 ORM 표준 JPA 프로그래밍").toString());
		log.debug(bookRepository.selectByName("자바 ORM 표준 JPA 프로그래밍").toString());
	}
}

 

 

실행하면 다음과 같이 이름으로 조회하는 동일한 결과가 나오게 됩니다.

 

Hibernate: 
    /* select
        generatedAlias0 
    from
        BookEntity as generatedAlias0 
    where
        generatedAlias0.name=:param0 */ select
            bookentity0_.book_id as book_id1_0_,
            bookentity0_.name as name2_0_,
            bookentity0_.price as price3_0_,
            bookentity0_.publisher as publishe4_0_ 
        from
            book bookentity0_ 
        where
            bookentity0_.name=?
DEBUG: com.spring.jpa_mybatis.bookTest - [BookEntity(id=1, name=자바 ORM 표준 JPA 프로그래밍, price=38700, publisher=에어콘출판)]
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectByName - ==>  Preparing: select book_id, name, price, publisher from book where name = ?
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectByName - ==> Parameters: 자바 ORM 표준 JPA 프로그래밍(String)
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectByName - <==      Total: 1
DEBUG: com.spring.jpa_mybatis.bookTest - [BookDto(bookId=1, name=자바 ORM 표준 JPA 프로그래밍, price=38700, publisher=에어콘출판)]

 

 

  • UPDATE
package com.spring.jpa_mybatis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.spring.jpa_mybatis.config.RootContext;
import com.spring.jpa_mybatis.dto.BookDto;
import com.spring.jpa_mybatis.entity.BookEntity;
import com.spring.jpa_mybatis.repository.BookJpaRepository;
import com.spring.jpa_mybatis.repository.BookRepository;

import lombok.extern.slf4j.Slf4j;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = RootContext.class)
@Slf4j
public class bookTest {
	
	@Autowired
	BookJpaRepository bookJpaRepository; // jpa
	
	@Autowired
	BookRepository bookRepository; // mybatis
	
	@Test
	public void jpa_mybatis_update() {
		BookEntity bookEntity = bookJpaRepository.findById(1).get();
		bookEntity.setPrice(40000);
		bookJpaRepository.save(bookEntity);
		
		BookDto bookDto = bookRepository.selectByBookId(2);
		bookDto.setPrice(46300);
		bookRepository.update(bookDto);
		
		log.debug(bookJpaRepository.findAll().toString());
		log.debug(bookRepository.selectAll().toString());
	}
}

 

 

JPA로는 1번 아이디의 책, MyBatis로는 2번 아이디의 책의 데이터를 수정하는 코드입니다.

 

실행하면 책들의 가격이 변경되어 조회되는 것을 확인할 수 있습니다.

 

Hibernate: 
    select
        bookentity0_.book_id as book_id1_0_0_,
        bookentity0_.name as name2_0_0_,
        bookentity0_.price as price3_0_0_,
        bookentity0_.publisher as publishe4_0_0_ 
    from
        book bookentity0_ 
    where
        bookentity0_.book_id=?
Hibernate: 
    /* load com.spring.jpa_mybatis.entity.BookEntity */ select
        bookentity0_.book_id as book_id1_0_0_,
        bookentity0_.name as name2_0_0_,
        bookentity0_.price as price3_0_0_,
        bookentity0_.publisher as publishe4_0_0_ 
    from
        book bookentity0_ 
    where
        bookentity0_.book_id=?
Hibernate: 
    /* update
        com.spring.jpa_mybatis.entity.BookEntity */ update
            book 
        set
            name=?,
            price=?,
            publisher=? 
        where
            book_id=?
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectByBookId - ==>  Preparing: select book_id, name, price, publisher from book where book_id = ?
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectByBookId - ==> Parameters: 2(Integer)
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectByBookId - <==      Total: 1
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.update - ==>  Preparing: update book set name = ?, price = ?, publisher = ? where book_id = ?
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.update - ==> Parameters: 배워서 바로 쓰는 스프링 프레임워크(String), 46300(Integer), 한빛미디어(String), 2(Integer)
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.update - <==    Updates: 1
Hibernate: 
    /* select
        generatedAlias0 
    from
        BookEntity as generatedAlias0 */ select
            bookentity0_.book_id as book_id1_0_,
            bookentity0_.name as name2_0_,
            bookentity0_.price as price3_0_,
            bookentity0_.publisher as publishe4_0_ 
        from
            book bookentity0_
DEBUG: com.spring.jpa_mybatis.bookTest - [BookEntity(id=1, name=자바 ORM 표준 JPA 프로그래밍, price=40000, publisher=에어콘출판), BookEntity(id=2, name=배워서 바로 쓰는 스프링 프레임워크, price=46300, publisher=한빛미디어)]
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - ==>  Preparing: select book_id, name, price, publisher from book
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - ==> Parameters: 
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - <==      Total: 2
DEBUG: com.spring.jpa_mybatis.bookTest - [BookDto(bookId=1, name=자바 ORM 표준 JPA 프로그래밍, price=40000, publisher=에어콘출판), BookDto(bookId=2, name=배워서 바로 쓰는 스프링 프레임워크, price=46300, publisher=한빛미디어)]

 

 

  • DELETE
package com.spring.jpa_mybatis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.spring.jpa_mybatis.config.RootContext;
import com.spring.jpa_mybatis.dto.BookDto;
import com.spring.jpa_mybatis.entity.BookEntity;
import com.spring.jpa_mybatis.repository.BookJpaRepository;
import com.spring.jpa_mybatis.repository.BookRepository;

import lombok.extern.slf4j.Slf4j;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = RootContext.class)
@Slf4j
public class bookTest {
	
	@Autowired
	BookJpaRepository bookJpaRepository; // jpa
	
	@Autowired
	BookRepository bookRepository; // mybatis
	
	@Test
	public void jpa_mybatis_delete() {
		bookJpaRepository.deleteById(1);
		bookRepository.deleteByBookId(2);
		
		log.debug(bookJpaRepository.findAll().toString());
		log.debug(bookRepository.selectAll().toString());
	}
}

 

 

 

 

이제 마지막으로 데이터를 삭제해보겠습니다.

 

JPA로는 1번 아이디의 책, MyBatis로는 2번 아이디의 책을 삭제하겠습니다.

 

실행하면 다음과 같이 데이터가 삭제되고 어떤 데이터도 조회가 되지 않는 것을 확인할 수 있습니다.

 

Hibernate: 
    select
        bookentity0_.book_id as book_id1_0_0_,
        bookentity0_.name as name2_0_0_,
        bookentity0_.price as price3_0_0_,
        bookentity0_.publisher as publishe4_0_0_ 
    from
        book bookentity0_ 
    where
        bookentity0_.book_id=?
Hibernate: 
    /* delete com.spring.jpa_mybatis.entity.BookEntity */ delete 
        from
            book 
        where
            book_id=?
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.deleteByBookId - ==>  Preparing: delete from book where book_id = ?
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.deleteByBookId - ==> Parameters: 2(Integer)
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.deleteByBookId - <==    Updates: 1
Hibernate: 
    /* select
        generatedAlias0 
    from
        BookEntity as generatedAlias0 */ select
            bookentity0_.book_id as book_id1_0_,
            bookentity0_.name as name2_0_,
            bookentity0_.price as price3_0_,
            bookentity0_.publisher as publishe4_0_ 
        from
            book bookentity0_
DEBUG: com.spring.jpa_mybatis.bookTest - []
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - ==>  Preparing: select book_id, name, price, publisher from book
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - ==> Parameters: 
DEBUG: com.spring.jpa_mybatis.repository.BookRepository.selectAll - <==      Total: 0
DEBUG: com.spring.jpa_mybatis.bookTest - []

 

 

 

 

이상으로 DTO/엔티티를 분리하여 JPA와 MyBatis를 동시 사용하는 설정에 대해 간단하게 알아보는 시간이었습니다.

 

읽어주셔서 감사합니다.

728x90
반응형

댓글