DB 설치

Mysql 진행

나는 도커로 Mysql 설치했으나, 로컬에 설치해도 상관 없음

도커

docker run --name test-mysql -e MYSQL_ROOT_PASSWORD=root -p 55555:3306 -d mysql:8.1

로컬 포트는 55555 사용했다. 도커에서 Mysql 포트 3306 매핑한다.

 

DB 스키마 계정 생성

mysql -u root -p




CREATE DATABASE jpa CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'root' IDENTIFIED BY 'root';
GRANT ALL PRIVILEGES ON jpa.* TO 'root';

 

 

DB 접속 툴은 DBeaver

 

STS(이클립스) 기준

프레임워크 없이 단순 JPA만 실습하기 위한 프로젝트 설

 

 

메이븐 의존성 pom.xml



<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>jpa-basic</groupId>
    <artifactId>jpa-01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <hiberate.version>6.0.0.Final</hiberate.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hiberate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-hikaricp</artifactId>
            <version>${hiberate.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.21.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

영속성 유닛 설정

특이사항으로 이제 jakarta 패키지 명을 사용한다.

 



<?xml version="1.0" encoding="utf-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
    version="3.0">
    <persistence-unit name="studyjpa" transaction-type="RESOURCE_LOCAL">
        <properties>
            <!-- DB 연결 정보 -->
            <property name="jakarta.persistence.jdbc.driver"
                value="com.mysql.cj.jdbc.Driver" />
            <property name="jakarta.persistence.jdbc.url"
                value="jdbc:mysql://localhost:55555/jpa?characterEncoding=utf8" />
            <property name="jakarta.persistence.jdbc.user" value="root" />
            <property name="jakarta.persistence.jdbc.password" value="root" />
            <property name="hibernate.hikari.poolName" value="pool" />
            <property name="hibernate.hikari.maximumPoolSize" value="10" />
            <property name="hibernate.hikari.minimumIdle" value="10" />
            <property name="hibernate.hikari.connectionTimeout" value="1000" />
            <!--  MySql 방언 -->
            <property name="hibernate.dialect"
                value="org.hibernate.dialect.MySQLDialect" />
            <!-- SQL 출력 -->
            <property name="hibernate.show_sql" value="true" />
            <!-- SQL 이쁘게 출력 -->
            <property name="hibernate.format_sql" value="true" />
            <!-- 주석도 함께 출력 -->
            <property name="hibernate.use_sql_comments" value="true" />
            <!-- JPA 표준에 맞춘 새로운 키 생성 전략 사용 -->
            <property name="hibernate.id.new_generator_mappings" value="true" />
            <!-- 실습에서만 사용할 것, @Entity에 따라 DDL 명령을 자동 실행해 준다. -->
            <property name="hibernate.hbm2ddl.auto" value="create" />
        </properties>
    </persistence-unit>
</persistence>

 

logf4.xml



<?xml version="1.0" encoding="UTF-8"?>
<configuration status="debug">


    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{DEFAULT} %5p [%c] %m%n"/>
        </Console>
    </Appenders>
   
    <loggers>
        <root level="debug" additivity="true">
            <AppenderRef ref="console"/>
        </root>
    </loggers>


</configuration>

 

테스트



package study.jpa.entity;


import java.time.LocalDateTime;


import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;


@Entity
public class User {
        
        @Id
        @GeneratedValue
        private Long id;
        private String name;
        private LocalDateTime registDate;
        
        public Long getId() {
                return id;
        }
        public void setId(Long id) {
                this.id = id;
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public LocalDateTime getRegistDate() {
                return registDate;
        }
        public void setRegistDate(LocalDateTime registDate) {
                this.registDate = registDate;
        }
}



import java.time.LocalDateTime;


import org.apache.logging.log4j.*;


import jakarta.persistence.*;
import study.jpa.entity.User;


public class Main {
        static Logger logger = LogManager.getLogger();
        
        public static void main(String[] args) {
                
                
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("studyjpa");
                EntityManager em = emf.createEntityManager();
                EntityTransaction tx = em.getTransaction();
                
                try {
                        tx.begin();
                        
                        logger.info("#################로그 테스트#################");
                        User user = new User();
                        user.setName("홍길동");
                        user.setRegistDate(LocalDateTime.now());
                        em.persist(user);
                        
                        tx.commit();
                } catch (Exception e) {
                        tx.rollback();
                } finally {
                        em.close();
                }
                emf.close();
        }
}

 

 

 

 

 

 

 

'개발 > JPA' 카테고리의 다른 글

06 다양한 연관관계 매핑  (0) 2024.04.14
05 연관관계 매핑 기초  (1) 2024.03.22
04 엔티티 매핑  (1) 2024.02.26
03 영속성 관리  (1) 2024.02.19
02 JPA 소개  (0) 2023.12.01

+ Recent posts