hsqldb

DB/HSQLDB 2013. 1. 1. 11:46


1번째

 

 

데이터 베이스의 경우 Oracle , MS-SQL , MY-SQL , PostgreSQL 등등 많은 데이터 베이스가 존재 합니다.

사실 DB는 용도나 종류에 따라 여러가지 종류가 존재한다. 제대로 정리하면 시간좀 걸릴만큼...

그러나 실무에서는 회사에 따라, 용도에 따라, 기능에 따라 사용할 DB를 선택한다.

사실 우리가 흔히 말하는 DB라는것은 정확히 DBMS(DataBase Management System)으로 

데이터 베이스 관리 시스템으로 

Java의 MVC의 model에 해당하는 데이터 자체의 관리 시스템을 지칭합니다.

이 중에서 HSQL이라는 DBMS를 사용하는 법에 대해서 적을것입니다.

참고로 태클은 대 환영입니다.

HSQLDB라는것은 in-memory and disk-based 로 작동하며, Embedded and server modes 가 가능합니다. 
(위키디피아의 설명입니다)

It is best known for its small size, ability to execute completely in memory, and its speed. It can also run on free Java runtimes such as Kaffe.


즉, 작은 사이즈의 시스템에서 좋다고 되어있군요.

음... 제 입장에서는 데이터를 저장해야 하는 어플리케이션의 경우 XML로 저장하기엔 좀 양이 많고

일반 디스크 베이스 DB를 사용하기엔 좀 큰, 어정쩡한 사이즈의 데이터 관리에 매우 좋다고 생각합니다.

그러면 이 방식이 왜 좋으냐. 우선 기본적으로 CPU가 제일 빠르죠? 그담에는 캐시가 빠르고... 등등으로 계산하면

속도는 CPU>캐시>메인메모리>하드디스크>플로피디스크 가 성립하는데, HSQL의 경우

메인메모리에 상주하는 시스템으로 구성되어 있습니다.  이는 이론상 기존 DB보다 1000배는 빠르다고 하는데 과연.....

즉. 임베디드 시스템이나, 저용량 데이터에 유용하게 쓰이면 좋겠죠.

게다가 메모리 가격도 대폭 다운됐고, 64비트 OS등장으로 인한 메모리 사용량 제한도 없어졌고, 게다가 빠르기 까지!!

뭐. 단점도 나름 존재합니다만 장점이 더 좋아 보입니다.

그리고 HSQL에는 MODE라는게 존재하는데 각 상황에 따라 MODE를 달리 쓰는것을 말합니다

예를들면 memory mode와, stand-alone모드가 있는데 각각의 상황에 따라 다르게 쓰는것을 말합니다

자세한것은 

In-memory mode 
All database tables and indexes are kept in memory and never saved to disk. Before you ask why anyone would want a database that is lost at application termination, think about having a local cache for database data that you can query, sort, group, and update using standard SQL statements. 
Stand-alone mode 
The application creates a database connection using JDBC, and the HSQLDB engine runs inside the application, accessing the database files directly. There can be no concurrent users (the application has exclusive access to the database files), but there are no additional threads nor TCP connection overhead. Stand-alone is the preferred mode for many embedded applications. 
Server mode 
This is the standard client/server database configuration similar to other relational databases, allowing concurrent connections using TCP sockets. Most developers will want this mode as it allows any JDBC client to connect and query/update tables while the main application is still running. 
Web server mode 
HSQLDB can act as a Web server, accepting SQL queries though HTTP, or can run as a servlet inside any standard Web container, passing though firewalls or installed on a Web hosting service without involving the provider support team (and expensive database hosting options). As HTTP is stateless, there are no transactions in this mode. 


이것을 보고 참고하십시오 ...해석하기 귀찮습니다 -_-

대충 정리를 하자면

HSQL은 메모리와 파일 베이스 시스템으로 대형 파일 시스템에는 맞지 않으나 중,소용량, 

임베디드 시스템에 쓰기 좋고, 시대가 흐름에 따라 메모리 베이스 DB를 쓰기 좋아지는 

환경이 되었으며, XML만이 대세가 아니라는걸 말해보고 싶었기 때문에(?) 사용하는법을 알아보는 겁니다.


.... 모르는것보단 많이 아는게 나름 쓸모있고 좋잖아요? 


그래서 쓰는거죠 뭐 -_-a

대충 이놈이 뭔 놈인지 왜 쓰는지는 설명이 된 거(?) 같으니 다음에는 기본적인 세팅~~~방법들 ... 다~~필요없습니다!

.....(어제 예전 개콘 보다가 식신 김도마를 봐버려서. -_-)

세팅법에 대해 알아보겠습니다.
 
 


2번째
 
HSQL을 위한 세팅

첫번째로 HSQL을 다운받습니다. 

 여기서 다운이라는건 프로그램을 따로 다운 받는것이 아닙니다. Jar파일을 받아 Import하면 게임 셋.

 사이트는 http://sourceforge.net/project/showfiles.php?group_id=23316 이고

 여기서 다운 받으시면 됩니다. hsqldb.jar라고 있을터인데 이를 import 합니다. 

다음 file을 만들어 이를 세팅해야합니다. HSQL은 미리 말했지만 파일베이스,메모리베이스 DBMS입니다.

이는 인스톨 하지 않는 대신 어딘가의 기본 구조를 설정 해야한다는 말입니다.

저의 경우 프로젝트 폴더안의 /conf 폴더를 만들고 여기다가 설정을 했습니다.

만들어지는 파일의 경우 xxx.properties, xxx.scripts, xxx.log 등인데 사용자가 설정해야 하는 부분은

scripts파일이며 나머지는 HSQL이 관리하는 것이기 때문에 건드리지 않습니다.

그러면 scripts의 설정을 해야겠죠.


제 샘플 script의 경우 SampleMDB.scripts입니다.

내용을 보면

CREATE SCHEMA PUBLIC AUTHORIZATION DBA
CREATE MEMORY TABLE SAMPLE_TABLE(ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,STR_COL VARCHAR(256),NUM_COL INTEGER)
ALTER TABLE SAMPLE_TABLE ALTER COLUMN ID RESTART WITH 26
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
SET WRITE_DELAY 20
SET SCHEMA PUBLIC
INSERT INTO SAMPLE_TABLE VALUES(1,'GM',400)
INSERT INTO SAMPLE_TABLE VALUES(3,'Test',300)
INSERT INTO SAMPLE_TABLE VALUES(24,'Test',300)
INSERT INTO SAMPLE_TABLE VALUES(25,'GM',400)

이렇게 구성되어있습니다.

뭔가 복잡해 보이지만.

우선 insert를 제거하면

CREATE SCHEMA PUBLIC AUTHORIZATION DBA
CREATE MEMORY TABLE SAMPLE_TABLE(ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,STR_COL VARCHAR(256),NUM_COL INTEGER)
ALTER TABLE SAMPLE_TABLE ALTER COLUMN ID RESTART WITH 26
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
SET WRITE_DELAY 20
SET SCHEMA PUBLIC


이렇게 남습니다.

이 부분을 살펴보면 어디선가 많이 본 부분일 겁니다. 즉, 일반적인 DBMS의 소스부분이죠.

그렇다 함은 이 script를 기반으로 어플리케이션이 작동할때 이 정보를 바탕으로 테이블을 제작하고,

종료되면 다시 여기에 정보가 기록된다는 말 이겠죠. 바꿔말한다면 이 정보를 미리 사용자가 설정하여 쓸수도 있다는

말입니다.

어플리케이션의 쿼리 명령으로도 설정 가능합니다.

예를들면

 han.updateDB("CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)");

 이런식으로 scripts를 건들지 않고 어플리케이션 상에서 설정 할수도 있다는 말입니다.

 자 기본적인 HSQL세팅은 끝났습니다. 간단하죠?

 다음에는 이를 사용한 실제 사용에 대해 알아보겠습니다




3번째
 
이번에는 세팅에 따른 각종 옵션에 대한 설명을 해보겠습니다.

HSQL에는 많은 모드가 존재하는데 크게 서버클라 모드와 stand alone 모드가 존재합니다.

이것에 대해 알기 위해 HSQL 메뉴얼의 일부분을 번역, 편집 해 봤는데 스크롤이 기므로 

아래를 클릭하여 보시길 바랍니다.

HSQLDB can be run in a number of different ways.

HSQLDB는 여러방법으로 가동 할수 있다.

In general these are divided into Server Modes and In-Process Mode (also called Standalone Mode).

크게 Server Mode와 Process Mode(흔히말해 Standalone Mode) 가 있는데 ,

A different sub-program from the jar is used to run HSQLDB in each mode.

이는 각각의 Mode별로 다르다.

Each HSQLDB database consists of between 2 to 5 files, all named the same but with different extensions,

각각의 HSQLDB DB는 2~5개의 파일로 구성되어 있고, 같은 디렉토리에 존재 하며, 모든것의 이름은 같지만 확장명은 다르다

located in the same directory. For example, the database named "test" consists of the following files

예를들면 test라는 database라는 이름의 DB는 아래와 같은 파일을 생성한다.

test.properties

test.script

test.log

test.data

test.backup

 

The properties files contains general settings about the database.

프로퍼티 파일은 DB의 일반적인 설정부분이다.

The script file contains the definition of tables and other database objects, plus the data for non-cached tables.

스크립트 파일은 테이블과 DB object에 대한 정의 들에 대한 정보를 가지고있다.

The log file contains recent changes to the database.

로그파일은 최근 DB가 바뀐것에 대한 정보를 가진다( Memory상에서 바뀌고 저장하기전까지 로그에 저장되어있다가 script로 옮겨진다)

The data file contains the data for cached tables and the backup file is a zipped backup of the last known consistent state of the data file.

요건 잘 모르겠다.

All these files are essential and should never be deleted.

이 파일들은 핵심적인파일이고 절대 지우면 안됀다.

If the database has no cached tables, the test.data and test.backup files will not be present.

만일 DB가 cached tables가 아니라면 .data,.backup 파일은 생성되지 않을것이다.

In addition to those files, HSQLDB database may link to any formatted text files, such as CSV lists, anywhere on the disk

게다가 이 파일들은 HSQLDB database는 CSV lists 처럼 어떤 text 포맷의 파일이라도 링크가 된다.


While the "test" database is operational, a test.log file is used to write the changes made to data.

test DB가 작동중일때, test.log 파일은 변경된 데이터들이 쓰이는데 사용된다.

This file is removed at a normal SHUTDOWN.

이 파일은 SHUTDOWN 일때 제거된다.

Otherwise (with abnormal shutdown) this file is used at the next startup to redo the changes.

한편 이 파일은 SHUTDOWN이후 다음 실행시 변경된다.

A test.lck file is also used to record the fact that the database is open.

test.lck 파일은 역시 DB가 open시에 기록하는데 사용된다.

This is deleted at a normal SHUTDOWN. In some circumstances, a test.data.old is created and deleted afterwards.

이것은 SHUTDOWN일때 삭제된다. 어떤 상황일때, test.data.old가 생성되고 이후것은 사라진다.

 

 

Server Modes

Server modes provide the maximum accessibility.

서버모드는 최대한의 접근을 제공한다.

The database engine runs in a JVM and listens for connections from programs on the same computer or other computers on the network.

DB엔진은 JVM내에서나 과 같은 컴퓨터나 다른 네트워크의 컴퓨터의 프로그램에서 connection을 위해 listens 중일때 작동한다.

Several different programs can connect to the server and retrieve or update information.

여러 다른 프로그램에서 서버로 연결할수 있거나 복구, update할수 있다.

Applications programs (clients) connect to the server using the HSQLDB JDBC driver.

client 가 server로 연결하기 위해 HSQLDB JDBC 드라이버를 사용한다.

In most server modes, the server can serve up to 10 databases that are specified at the time of running the server.

많은 server mode에서  서버는 running server time을 10으로 둔다.

Server modes can use preset properties or command line arguments as detailed in the Advanced Topics chapter.

server mode는 프로퍼티를 미리 세팅할수 있다.

There are three server modes, based on the protocol used for communications between the client and server.

3가지 서버모드가 있는데 이는 client-server 통신 을 위한 프로토콜을 기본으로 하고있다.


Hsqldb Server


This is the preferred way of running a database server and the fastest one.

이것은 가장 빠른 DB server를 준비하는 방법이다.

A proprietary communications protocol is used for this mode.

독점적인(?) 통신 프로토콜이 사용된다.


    java -cp ../lib/hsqldb.jar org.hsqldb.Server -database.0 mydb -dbname.0 xdb

Hsqldb Web Server

This mode is used when access to the computer hosting the database server is restricted to the HTTP protocol.

이 모드는 http 프로토콜로 제한된 DB 서버 컴퓨터 호스팅에 접속하기 위한 모드이다.

The only reason for using the Web Server mode is restrictions imposed by firewalls on the client or server machines

클라이언트나 서버머신의 방화벽으로 인한 제한된 웹서버 모드를 사용하기 위한 목적이다.


    org.hsqldb.WebServer

Hsqldb Servlet

This uses the same protocol as the Web Server.

웹서버 프로토콜과 같은것을 사용한다.

The Servlet mode can serve only a single database.

서블릿모드는 하나의 DB만 제공한다.

Please note that you do not normally use this mode if you are using the database engine in an application server.

중요한건 이 모드는 어플리케이션 서버에서는 사용하면 작동하지 않는다는 것이다.(서블릿 모드다)


Example 1.1. Java code to connect to the local Server above

    try {
        Class.forName("org.hsqldb.jdbcDriver" );
    } catch (Exception e) {
        System.out.println("ERROR: failed to load HSQLDB JDBC driver.");
        e.printStackTrace();
        return;
    }

    Connection c = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/xdb", "sa", "");

In some circumstances, you may have to use the following line to get the driver.

어떤상황에서는 저런식으로 드라이버를 가져온다.

    Class.forName("org.hsqldb.jdbcDriver").newInstance();


In-Process (Standalone) Mode

This mode runs the database engine as part of your application program in the same Java Virtual Machine.

이 모드는 어플리케이션과 같은 JVM을 사용하는 DB에서 사용하는것이다.

For most applications this mode can be faster, as the data is not converted and sent over the network.

대부분의 어플리케이션은 이 모드가 더 빠르나 네트워크로 전송할수있게 변환할수가 없는 문제가 있다.

The recommended way of using the in-process mode in an application is to use an HSQLDB Server instance for the database while developing the application and then switch to In-Process mode for deployment.
이 방법은 개발중인 어플리케이션이나, 긴급하게 쓸때 사용하는것을 추천한다(-_-)


    Connection c = DriverManager.getConnection("jdbc:hsqldb:file:testdb", "sa", "");

    Connection c = DriverManager.getConnection("jdbc:hsqldb:file:/opt/db/testdb", "sa", "");

Memory-Only Databases


It is possible to run HSQLDB in a way that the database is not persistent and exists entirely in random access memory.

이 모드는 DB가 변하지 않거나 램에 계속 존재할때 사용한다.


디스크에 정보를 저장하지 않으므로 내부 application data에 사용할때나 쓰자. 애플릿 같은데서 (-_-)

    Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:aname", "sa", "");

 





4번째
 
자 그럼 샘플을 하나 맹글어 보도록 하죠. 여기서는 stand-alone 방식을 사용한 DB를 호출합니다.

우선 jar 파일을 import 합니다.




 

이후 설정을 해주면 되겠죠.


 

우선 드라이버를 로드합니다 여기에서는 프로퍼티를 통한 로드를 하였기때문에 보이진 않습니다만 정식 루트는

Class.forName("org.hsqldb.jdbcDriver");로  해주시면 되겠습니다.

다음은 connection을 가져옵니다.

 


경로는 프로젝트 하단의 /conf 폴더에 sampleMDB라는 DB명을 사용한다고 설정합니다.

그런데 이중에 경로 설정이 좀 특이하죠? 이는 리눅스랑 윈도우가 각각 / \ 를 사용하기 때문에 어디든지

돌아갈수 있게 하기 위해 위와 같이 설정을 합니다.

그리고 이젠 DB에서 쿼리문을 통한 데이터를 불러와보도록 하죠.


 

쿼리문을 실행하는 메서드를 호출하는 부분입니다. 메서드로 가볼까요.

 


 

위와 같이 메서드에 쿼리문을 받아 실행하는 부분입니다.

그럼 위와같이 했을때 결과와 시작을 볼까요?


초기의 SampleMDB.scripts 파일입니다. 유저가 설정하는 부분으로 이것은 툴을 사용해 만들어도 무방합니다.

 

이후 실행을 합니다.

 

 



보시다시피 쿼리로 Insert된 부분이 삽입 되어 있습니다.

이것으로 DB에 올바른 처리가 됨을 확인할수 있습니다.

 




5번째
 
여기서는 사용한 샘플소스의 위치나 주의점에 대해 말씀드리겠습니다

샘플소스는 여기

http://hsqldb.org/doc/guide/apb.html

이며 이것을 사용한 것은 가장 기본적인 것이기 때문에

( 제꺼는 자카르타 log4j + Pool + DBUtil 을 섞어 커스터마이징을 해서 이리저리 설명하기엔 약간의 문제가 있는터라

기본적인 것을 사용했습니다)

이를 활용하면 얼마든지 활용이 가능하기 때문입니다.







주의할 점은 모든 수행이후 SHUTDOWN 쿼리를 날려주라는 것입니다.

그렇지 않을경우 아무리 쿼리를 날려도 메모리상에서만 처리가 되며 프로그램 종료후 무엇을 하던

저장이 되지않는다는 것입니다.


외국 블로그에서 찾은건데 여기도 주의사항으로 꼭 SHUTDOWN을 하라는 말이 있군요

http://eranga.blogspot.com/2006/11/persisting-hsql-data.html

stmt.execute("SHUTDOWN");// Very important








그리고 stand-alone(다른것은 잘 모르겠음) 의 경우 1 connect 밖에 허용하지 않으므로

2개가 동시에 접근을 못한다는 문제가 있습니다. 이를 주의하시길
 
 

hsqldb 설치

http://www.hsqldb.org/web/hsqlDocsFrame.html의 문서를 기준으로 설치할 수도 있지만 우리의 목적은 hsqldb를 이용한 테스트이므로 다른 자바 개발자 사이트에서 제시한 보다 간단하고 빠른 방법으로 설치와 실행을 해보는 게 좋겠다.

hsqldb 다운로드

공식 사이트 http://www.hsqldb.org/를 가보면 최근 버전은 1.8.0.10(2008-12-28)이다.
http://sourceforge.net/projects/hsqldb로 가서 "files" 링크를 클릭하여 최신 버전을 다운로드 받는다.
설치하는 과정은 아주 간단하다. 다운로드 받은 zip 파일을 풀고 lib 디렉토리 안에 있는 hsqldb.jar 파일을 실행에 사용할 수 있는 적당한 디렉토리(클래스 패스)에 위치시키면 된다.



hsqldb 사용하기


hsqldb 실행

Server 모드와 In-process 모드, 2가지의 실행 모드가 있다. 여기서는 Server 모드의 실행 모드만 다루도록 한다.

  • Server 모드: 독립된 서버 프로세스로 실행. 로컬 또는 원격지 호스트에서 hsqldb에 접근할 수 있다.
  • In-process 모드: hsqldb를 사용하는 어플리케이션과 동일한 프로세스에서 hsqldb를 실행하는 모드. 자체 DB를 필요로 하는 어플리케이션이나 캐시와 같은 임시 데이터를 처리하는 데 이용

Server 모드는 Server, WebServer, Servlet의 3가지 방식이 있는데, 이 글에서는 Server 방식만 다루겠다.

실행 방법은 hsqldb.jar 파일을 클래스 패스에 추가하여 org.hsqldb.Server 클래스를 실행시키면 된다.

% java -classpath hsqldb/lib/hsqldb.jar org.hsqldb.Server



데이터베이스 생성과 사용

hsqldb는 데이터베이스 생성과 사용이 하나의 명령어로 실행된다. '-database.[n]' 옵션으로 Server를 실행하면 지정한 데이테베이스가 없으면 새로 만들고, 있으면 기존 데이터베이스를 사용한다.

% java -classpath hsqldb/lib/hsqldb.jar org.hsqldb.Server -database.0 file:data/test -dbname.0 asiavant

'-database.0 file:data/test' 옵션
데이터베이스가 사용할 경로와 파일명 형식(test.*)을 명시
'-dbname.0 asiavant' 옵션
데이터베이스의 alias를 지정. alias는 어플리케이션에서 jdbc를 통해 hsqldb에 접근할 때 사용. 위 예에서 jdbc connection url은 'jdbc:hsqldb:hsql://localhost/asiavant'

Server를 실행한 디렉토리를 보면 'data'라는 디렉토리에 'test'로 시작하는 파일들이(test.log, test.properties) 생성되어 있는 것을 확인할 수 있다.
각 옵션 뒤에 붙는 '.0'은 데이터베이스의 인덱스를 의미. hsqldb는 0~9 사이의 인덱스 값을 허용하므로 전체 10개의 데이터베이스를 동시에 띄울 수 있다.

server.properties 파일을 이용한 서버 실행

hsqldb는 Server를 실행할 때 지정한 디렉토리에 server.properites 파일이 있는지 검사하여 있으면 Server 설정 정보를 읽어서 Server를 실행시킨다.

server.database.0=file:data/testserver.dbname.0=asiavantserver.database.1=file:/Users/Hugo/data/tempserver.dbname.1=sampleserver.trace=true


이렇게 해두면 Server를 실행할 때마다 동일한 옵션을 반복해서 입력할 필요가 없어진다.

Database Manager

hsqldb는 데이터베이스에 query를 하거나 데이터베이스 오브젝트를 볼 수 있게 해주는 GUI 툴을 제공한다.

% java - classpath lib/hsqldb.jar org.hsqldb.util.DatabaseManager

URL 필드에 hsqldb url 정보를 입력한다. 여기서는 jdbc:hsqldb:hsql://localhost/asiavant

데이터베이스 연결에 성공하면 아래와 같이 SQL을 실행할 수 있는 윈도우가 뜬다. query를 입력한 후 'Execute' 버튼을 눌러서 query를 실행한다.

hsqldb 서버 종료하기

hsqldb를 정상적으로 종료하려면 DataManager에서 'shutdown' query를 실행한다. 또는 hsqldb Server를 실행시킨 터미널에서 '[Ctrl] + [C]'를 눌러서 종료할 수도 있으나 이 경우엔 비정상적으로 종료될 수도 있다.


출처 - http://devx.tistory.com/entry/HSQL-hyper-SQL-%EC%82%AC%EC%9A%A9%EB%B2%95



Posted by linuxism
,