본문 바로가기
프로그램/스프링

1. JPA 실습환경 셋팅

by cbwstar 2021. 5. 26.
728x90
반응형

1.1 스프링 부트 사이트에서 스프링부트를 다운 받아서 설치한다.

1.2 프로젝트 생성

     File > New > Spring Starter Project

프로젝트명 입력

디펜던시 선택 : PostgresSQL Driver,Spring Web,Lombok,Spring Boot DevTools,MySQL Driver,Spring Data JPA

Finish 버튼 클릭

1.3 데이터베이스 및 테이블 생성

    MySql기준으로 테이블을 생성합니다.

    PostgreSQL DB는 서로 다른 2개의 데이터 베이스 테스트용으로 추가 하였습니다.

    작업은 MySql기준 입니다.

1.4 MySql db를 다운받아서 로컬 pc에 설치합니다.

    MySql 접속후 사용자 계정을 생성합니다.

/* mysql 접속 */
mysql -u root -p

use mysql;
/* 사용자 확인 */
select * from user;

/* 사용자 계정 생성 */
create user 'cbw'@'%' identified by 'cbw';

/* db 생성 */
create database cbw-jpa DEFAULT CHARACTER SET utf8;

/* 생성된 데이터 베이스 확인 */
show databases;

/* 생성된 db에 사용자 접속권한 부여 */
GRANT ALL PRIVILEGES ON cbw_jpa.* TO 'cbw'@'%';

/* 모든 db에 접속권한 부여 */
GRANT ALL PRIVILEGES ON *.* TO 'cbw'@'%';

flush privileges;


use cbw_jpa;

/* 테이블 생성 */
CREATE TABLE `dept` (
        `deptno` INT(11) NOT NULL,
        `dname` VARCHAR(14) NOT NULL,
        `loc` VARCHAR(13) NULL DEFAULT NULL,
        PRIMARY KEY (`deptno`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

CREATE TABLE `emp` (
        `empno` INT(11) NOT NULL,
        `comm` DOUBLE NULL DEFAULT NULL,
        `ename` VARCHAR(10) NOT NULL,
        `hiredate` DATE NULL DEFAULT NULL,
        `job` VARCHAR(9) NULL DEFAULT NULL,
        `sal` DOUBLE NULL DEFAULT NULL,
        `deptno` INT(11) NULL DEFAULT NULL,
        `mgr` INT(11) NULL DEFAULT NULL,
        PRIMARY KEY (`empno`),
        INDEX `idx_deptno` (`deptno`),
        INDEX `idx_mgr` (`mgr`),
        CONSTRAINT `FK_mgr` FOREIGN KEY (`mgr`)
                REFERENCES `emp` (`empno`),
        CONSTRAINT `FK_deptno` FOREIGN KEY (`deptno`)
                REFERENCES `dept` (`deptno`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

CREATE TABLE `salgrade` (
        `grade` INT(11) NOT NULL,
        `hisal` DOUBLE NOT NULL,
        `losal` DOUBLE NOT NULL,
        PRIMARY KEY (`grade`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

1.5 테스트 데이터 입력

INSERT INTO SALGRADE(grade, losal, hisal) VALUES (1, 700,1200);
INSERT INTO SALGRADE(grade, losal, hisal) VALUES (2,1201,1400);
INSERT INTO SALGRADE(grade, losal, hisal) VALUES (3,1401,2000);
INSERT INTO SALGRADE(grade, losal, hisal) VALUES (4,2001,3000);
INSERT INTO SALGRADE(grade, losal, hisal) VALUES (5,3001,9999);

INSERT INTO DEPT(deptno, dname, loc) VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT(deptno, dname, loc) VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT(deptno, dname, loc) VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT(deptno, dname, loc) VALUES (40,'OPERATIONS','BOSTON');

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7839,'KING','PRESIDENT', NULL,STR_TO_DATE('17-11-1981','%d-%m-%Y'),5000,NULL,10);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7566,'JONES','MANAGER',  7839,STR_TO_DATE('2-4-1981',  '%d-%m-%Y'),2975,NULL,20);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7698,'BLAKE','MANAGER',  7839,STR_TO_DATE('1-5-1981',  '%d-%m-%Y'),2850,NULL,30);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7782,'CLARK','MANAGER',  7839,STR_TO_DATE('9-6-1981',  '%d-%m-%Y'),2450,NULL,10);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7902,'FORD','ANALYST',   7566,STR_TO_DATE('3-12-1981', '%d-%m-%Y'),3000,NULL,20);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7788,'SCOTT','ANALYST',  7566,STR_TO_DATE('13-07-1987', '%d-%m-%Y'),3000,NULL,20);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7499,'ALLEN','SALESMAN', 7698,STR_TO_DATE('20-2-1981', '%d-%m-%Y'),1600,300,30);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7521,'WARD','SALESMAN',  7698,STR_TO_DATE('22-2-1981', '%d-%m-%Y'),1250,500,30);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7654,'MARTIN','SALESMAN',7698,STR_TO_DATE('28-9-1981', '%d-%m-%Y'),1250,1400,30);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7844,'TURNER','SALESMAN',7698,STR_TO_DATE('8-9-1981',  '%d-%m-%Y'),1500,0,30);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7900,'JAMES','CLERK',    7698,STR_TO_DATE('3-12-1981', '%d-%m-%Y'),950,NULL,30);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7934,'MILLER','CLERK',   7782,STR_TO_DATE('23-1-1982', '%d-%m-%Y'),1300,NULL,10);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7369,'SMITH','CLERK',    7902,STR_TO_DATE('17-12-1980','%d-%m-%Y'),800,NULL,20);

INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
VALUES(7876,'ADAMS','CLERK',    7788,STR_TO_DATE('13-07-1987', '%d-%m-%Y'),1100,NULL,20);

1.6 프로젝트 환경설정

applicatin.properties

# DATASOURCE
spring.datasource.platform=mysql
spring.datasource.sqlScriptEncoding=UTF-8
spring.datasource.url=jdbc:log4jdbc:mysql://localhost:3306/cbw_jpa?createDatabaseIfNotExist=true&serverTimezone=Asia/Seoul
spring.datasource.username=cbw
spring.datasource.password=cbw
spring.datasource.driver-class-name=net.sf.log4jdbc.sql.jdbcapi.DriverSpy

# JPA
# 엔티티 클래스를 바탕으로 테이블을 생성하거나 수정하는 기능은 사용하지 않습니다.
spring.jpa.hibernate.ddl-auto=none

spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.data.jpa.repositories.enabled=true

# Logging
logging.config=classpath:logback.xml

1.7 logback.xml 설정

resources 폴더에 파일 생성

<?xml version="1.0" encoding="UTF-8"?>
<!-- configuration file for LogBack (slf4J implementation)
See here for more details: http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/ -->
<configuration scan="true" scanPeriod="30 seconds">

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>

    <!-- To enable JMX Management -->
    <jmxConfigurator/>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%-5level [%d] [%logger{50}][%t] - %msg%n</pattern>
        </encoder>
    </appender>
    
    <logger name="com.terry.securityjpa" level="debug" additivity="false">
    	<appender-ref ref="console" /> 
    </logger>
    <logger name="org.hibernate" level="info" additivity="false">
    	<appender-ref ref="console" /> 
    </logger>
    <logger name="org.springframework.security" level="debug" additivity="false">
    	<appender-ref ref="console" /> 
    </logger>
    <logger name="org.springframework" level="info" additivity="false">
    	<appender-ref ref="console" /> 
    </logger>
    <logger name="javax.sql" level="info" additivity="false">
    	<appender-ref ref="console" /> 
    </logger>
    
    <!-- log4jdbc setting(turn on : info or debug, turn off : fatal -->
    <logger name="jdbc.sqlonly" level="off" additivity="false"> 
    	<appender-ref ref="console" /> 
  	</logger> 
  	<logger name="jdbc.sqltiming" level="info" additivity="false">
  		<appender-ref ref="console" />
  	</logger>
  	<logger name="jdbc.audit" level="off" additivity="false" />  
  	<logger name="jdbc.resultset" level="off" additivity="false" />   
  	<logger name="jdbc.resultsettable" level="off" additivity="false" />   
  	<logger name="jdbc.connection" level="off" additivity="false" />  
    
    <root level="info">
    	<appender-ref ref="console" />
    </root>
    
</configuration>

1.8 pom.xml

<!-- 추가된 라이브러리들 시작-->
        <dependency>
            <groupId>org.bgee.log4jdbc-log4j2</groupId>
            <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
            <version>1.16</version>
        </dependency>
        
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
        </dependency>
        
        <dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-sql-spring</artifactId>
<version>${querydsl.version}</version>
</dependency>
     <!-- 추가된 라이브러리들 끝-->

 

<!-- 추가된 플러그인 시작 -->
<plugin>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-maven-plugin</artifactId>
<version>${querydsl.version}</version>
<executions>
<execution>
<goals>
<goal>export</goal>
</goals>
</execution>
</executions>
<configuration>
    <!-- mysql db 접속 Q타입 클래스 생성 --> 
<jdbcDriver>com.mysql.cj.jdbc.Driver</jdbcDriver>
<jdbcUrl>jdbc:mysql://localhost:3306/cbw_jpa</jdbcUrl>
<jdbcUser>cbw</jdbcUser>
<jdbcPassword>cbw</jdbcPassword>

<!-- postgresql db 접속 Q타입 클래스 생성 --> 
<!-- 
<jdbcDriver>org.postgresql.Driver</jdbcDriver>
<jdbcUrl>jdbc:postgresql://localhost:5432/cbw</jdbcUrl>
<jdbcUser>cbw</jdbcUser>
<jdbcPassword>cbw</jdbcPassword>
-->

<packageName>cbw.jpa.domain.entity</packageName>
<targetFolder>target/generatedsources/java</targetFolder>
<namePrefix>S</namePrefix>
<exportBeans>true</exportBeans>
<tableNamePattern>dept,emp,salgrade</tableNamePattern>
<!-- targetFolder에 Dept.java, Emp.java를 생성 -->
</configuration>
<dependencies>
<dependency>
   <!-- 
    <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.19</version>
            <scope>compile</scope>
            -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
<scope>compile</scope>
</dependency>
</dependencies>
</plugin>
<!-- 추가된 플러그인 끝 -->

 

<namePrefix>S</namePrefix>

명시적으로 설정하지 않으면 두문자 'Q'를 사용하여 Q 타입 클래스를 생성합니다. 변경할 수 있습니다.

 

<exportBeans>true</exportBeans>

테이블 스키마를 바탕으로 모델클래스를 생성할 수 있습니다.

 

<tableNamePatten>dept,emp,salgrade</tableNamePattern>

테이블명을 콤마로 구분해서 대상 테이블들을 지정합니다. 테이블명을 인식 못할경우 대문자로 설정해야 인식하니 Q타입 클래스가 생성되지 않는 경우 대문자로 바꾸어서 하시길 바랍니다.

 

1.9 Q 타입 클래스 생성

Maven generate-sources 클릭

정상적으로 QType클래스가 생성되면 target/generatedsources/java 폴더에 파일이 생성됩니다.

 

728x90
반응형

'프로그램 > 스프링' 카테고리의 다른 글

모델1-기본테이블 생성  (0) 2021.06.22
엔티티 생성 및 기본 테스트  (0) 2021.06.22
pom.xml  (0) 2021.06.22
persistence.xml  (0) 2021.06.22
Spring Data JPA 사용 및 설정  (0) 2021.06.01

댓글



"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

loading