- [spring boot 2.1.7] 개발 준비

  - [spring boot 2.1.7] profile 및 logback 설정

  - [spring boot 2.1.7] JSP 설정

  - [spring boot 2.1.7] thymelef 설정

  - [spring boot 2.1.7] mybatis - mysql 5.7 연동

  - [spring boot 2.1.7] hibernate - mysql 5.7 연동 설정

 

 

소스 : https://github.com/yamoe/spring-boot-example/tree/master/06.hibernate-mysql/arti

https://yamoe.tistory.com/540 에 이어서 작성. (소스 및 mysql 세팅)

 

 

* Spring Boot 연동 준비

- build.gradle 설정 추가

// hibernate
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

// mysql
implementation 'mysql:mysql-connector-java'

 

- mssql 연결 정보 추가 : 각 환경별(dev, alpha, prod) db.xml

spring:
  jpa-mysql:
    datasource:
      hikari:
        jdbc-url: jdbc:mysql://192.168.56.101:3306/testdb?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC
        username: user1
        password: user1A!@#
        driver-class-name: com.mysql.cj.jdbc.Driver
        minimum-idle: 1
        maximum-pool-size: 10
        connection-timeout: 20000
        idle-timeout: 300000
        max-lifetime: 1200000
        auto-commit: true
        connection-test-query: SELECT 1 FROM DUAL
  jpa:
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    generate-ddl: false
    open-in-view: false
    properties:
      hibernate:
        show_sql: true
        format_sql: true
        use_sql_comments: true

logging:
  level:
    org:
      hibernate:
        SQL: DEBUG
        type:
          descriptor:
            sql: trace

 

 

* 소스 작성

<JpaDatabaseConfig.java>
DB 연결 정보 설정 class

package com.example.arti.jpa.config;

import com.example.arti.config.yaml.YamlPropertySourceFactory;
import com.zaxxer.hikari.HikariDataSource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "jpaEntityManagerFactory",
        transactionManagerRef = "jpaTransactionManager",
        basePackages = {"com.example.arti.jpa.repo"})
@PropertySource(value = {
        "classpath:/db.yml"
}, ignoreResourceNotFound = true, factory = YamlPropertySourceFactory.class)
public class JpaDatabaseConfig {

    @Bean(name = "jpaDataSource")
    @ConfigurationProperties(prefix = "spring.jpa-mysql.datasource.hikari")
    public DataSource jpaDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }


    @Bean(name = "jpaEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean jpaEntityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("jpaDataSource") DataSource dataSource) {

        // package 는 @Entity 가 정의된 클래스의 상위 패키지명 지정
        return builder.dataSource(dataSource).packages("com.example.arti.jpa.entity").build();
    }

    @Bean(name = "jpaTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("jpaEntityManagerFactory") EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);

        return transactionManager;
    }


}

 

<Test.java>
entity 클래스 (table 매핑)

package com.example.arti.jpa.entity;

import lombok.Data;

import javax.persistence.*;
import java.sql.Timestamp;

@Data
@Entity
@Table(name = "test")
public class Test {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String str;

    private Timestamp date;
}

 


<JpaTestRepository.java>
CRUD 용 레파지토리

package com.example.arti.jpa.repo;

import com.example.arti.jpa.entity.Test;
import org.springframework.data.jpa.repository.JpaRepository;

public interface JpaTestRepository extends JpaRepository<Test, Long> {
}

 

<JpaController.java>
테스트용 컨트롤러 

package com.example.arti.jpa.controller;

import com.example.arti.jpa.service.JpaTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "jpa")
public class JpaController {

    @Autowired
    private JpaTestService svc;

    @RequestMapping("/select")
    public @ResponseBody String select() throws Exception {
        return svc.select().toString();
    }

}

 

 

<JpaTestService.java>
테스트용 서비스 

package com.example.arti.jpa.service;


import com.example.arti.jpa.entity.Test;
import com.example.arti.jpa.repo.JpaTestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JpaTestService {

    @Autowired
    JpaTestRepository repo;

    public List<Test> select() throws Exception {
        return repo.findAll();
    }
}

 

 

* 실행

http://localhost:9999/jpa/select

 

 

* 참고

https://jsonobject.tistory.com/449
https://velog.io/@kingcjy/Spring-Boot-JPA-DB-Replication-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0
http://wonwoo.ml/index.php/post/780
https://www.popit.kr/%EC%8A%A4%ED%94%84%EB%A7%81-%EB%B6%80%ED%8A%B8-auto-configuration%EA%B3%BC-jpa%ED%95%98%EC%9D%B4%EB%B2%84%EB%84%A4%EC%9D%B4%ED%8A%B8-sql%EB%AC%B8-%EB%A1%9C%EA%B9%85/