팀 프로젝트를 위한 JPA 공부 (1단계의 entity 패키지 [테스트])

이리·2022년 2월 25일
0

이전 포스팅에서 만들었던 entity패키지의 클래스들이 잘 동작하는 지 확인하고 싶었다.
테스트 코드를 이용하여 하나씩 알아가보려고 한다.


🚀 Code

  1. exist
@SpringBootTest
//@Transactional
//@Rollback(value = false)
@Slf4j
public class EntityTests1 {

	@PersistenceContext
	EntityManager em;

	@Test
	void testExist(){

	}

}
Hibernate: 
    
    create table hibernate_sequence (
       next_val bigint
    ) engine=InnoDB
Hibernate: 
    
    insert into hibernate_sequence values ( 1 )
Hibernate: 
    
    create table member (
       member_id bigint not null,
        created_date datetime(6),
        last_modified_date datetime(6),
        created_by varchar(255),
        last_modified_by varchar(255),
        age integer not null,
        username varchar(255),
        team_id bigint,
        primary key (member_id)
    ) engine=InnoDB
Hibernate: 
    
    create table team (
       team_id bigint not null,
        created_date datetime(6),
        updated_date datetime(6),
        name varchar(255),
        primary key (team_id)
    ) engine=InnoDB
Hibernate: 
    
    alter table member 
       add constraint FKcjte2jn9pvo9ud2hyfgwcja0k 
       foreign key (team_id) 
       references team (team_id)

빈 테스트를 실행하였고, 테이블이 만들어졌다.(한번더 실행하면 당연히 아무 sql로그 안뜸)
기존에 내가 익숙하던 키생성전략(identify)을 사용하지 않아서인지
Auto_increment가 아닌 시퀀스 테이블이 별도로 만들어지는 것을 알 수 있다.


  1. 값 삽입 테스트
@SpringBootTest
@Transactional
@Rollback(value = false)
@Slf4j
public class EntityTests1 {

	@PersistenceContext
	EntityManager em;

	@Test
	void test(){
		Team teamA = new Team("teamA");

		em.persist(teamA);//buffer.write()라고 생각하면 편함
		em.flush();//영속성 컨텍스트와 DB 동기화(차이점 적용)
		em.clear();//em 비우기
	}
}
Hibernate: 
    select
        next_val as id_val 
    from
        hibernate_sequence for update
            
Hibernate: 
    update
        hibernate_sequence 
    set
        next_val= ? 
    where
        next_val=?
Hibernate: 
    insert 
    into
        team
        (created_date, updated_date, name, team_id) 
    values
        (?, ?, ?, ?)
2022-02-25 16:44:55.083  INFO 11608 --- [           main] o.s.t.c.transaction.TransactionContext   : Committed transaction for test: [DefaultTestContext@7bb6ab3a testClass = EntityTests1, testInstance = com.example.laboratoryidea.entity.EntityTests1@3c65f2e1, testMethod = test1@EntityTests1, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@7fe7c640 testClass = EntityTests1, locations = '{}', classes = '{class com.example.laboratoryidea.LaboratoryIdeaApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4ef74c30, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@13d9cbf5, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@7b50df34, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@19b843ba, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@74f6c5d8, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@10b48321], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
2022-02-25 16:44:55.101  INFO 11608 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-02-25 16:44:55.104  INFO 11608 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-02-25 16:44:55.122  INFO 11608 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0

일단 테이블에 삽입될 때마다 현재 시퀀스 값을 불러오고 다음 값으로 바꾼다.
그래서 auto_increment와 달리 테이블들 간에도 id값이 중복되지 않는다.
persist()로 변화를 지정하고, flush로 적용하고, clear로 비운다.
그 다음에 삽입하는 것이다.

profile
어제보다 나은 사람이 되자

0개의 댓글