윤개발

[JPA] H2 database 연결 & JPA 프로젝트 생성 본문

백엔드/JPA

[JPA] H2 database 연결 & JPA 프로젝트 생성

DEV_SJ 2020. 2. 22. 19:00

H2 database란?

 

h2 db는 MySQL, oracle 같은 관계형 데이터베이스이다.

h2 db는 이들과 다르게 경량 db이며 메모리가 매우 적다.

또한 db를 로컬에 저장하는 것이 아니라 메모리에 저장하는 것이기 때문에 테스트용으로만 써야한다.

 

 

H2 설치

h2 db 사이트: https://www.h2database.com/html/main.html

 

H2 Database Engine

H2 Database Engine Welcome to H2, the Java SQL database. The main features of H2 are: Very fast, open source, JDBC API Embedded and server modes; in-memory databases Browser based Console application Small footprint: around 2 MB jar file size     Support S

www.h2database.com

에서 Window installer를 선택하고 설치하면 설치가 끝난다.

 

H2 실행

설치가 완료되면 윈도우에서 h2 console (Command Line) 을 누르면 실행 되면서 아래그림과 같은 웹 창 하나가 뜬다.

 

연결을 누르면 실행이 완료된다.

 

프로젝트 생성 - 의존성 추가

InteliJ에서 Maven 프로젝트를 생성한다. (name, title등은 아무거나 지정)

 

생성된 프로젝트에서 pom.xml 파일을 찾아 아래 의존성을 추가한다. (당연하지만 의존성은 <project> </project> 안에 포함되어있어야함.)

1
2
3
4
5
6
7
8
9
10
11
12
     <dependencies>         
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.3.10.Final</version>
        </dependency>         
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.199</version>
        </dependency>
    </dependencies>
cs

 

그리고 resource 폴더에 META-INF 폴더를 생성한 후 persistence.xml 파일을 생성한다.

 

persistence.xml에 아래 내용을 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" 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_2.xsd">
    <persistence-unit name="hello">
        <properties> 
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.user" value="sa"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <!--opt -->
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.use_sql_comments" value="true"/>
            <!--<property name="hibernate.hbm2ddl.auto" value="update" />-->
        </properties>
    </persistence-unit>
</persistence>
cs

JPA 프로젝트 생성이 완료되었다.

'백엔드 > JPA' 카테고리의 다른 글

[JPA] Java Persistence API 소개  (0) 2020.02.17
Comments