shimashimaの日記: [Java][maven][DB]DBをmavenでエクスポート
プロジェクトの最中良くある話で、DBの中身をExcel形式でエクスポートしたくなることがある。DbUnitを利用しツールを作れば簡単にできる。が、ちょっと調べてみたところmavenでも可能なようなので試してみた。
もちろん、maven単体ではなにもできないのでpluginを利用する訳だが、今回利用するpluginはdbunit-maven-plugin。名前の通り、DbUnitのmaven用ラッパーのようだ。
mavenなのでpom.xmlを書く訳だが、dbunit-maven-pluginを利用するだけならば以下のように記述すればよい。下の例はOracle10gR2の場合。他のDBMSでも基本は同じだ。
POIを明示的に依存関係記述しているのは、dbunit-maven-pluginが依存しているDbUnitがこのバージョンのPOIに依存しているため。最新のPOIを試したがNoSuchMethodErrorがでる。
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>db</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>db</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>dbunit-maven-plugin</artifactId>
<version>1.0-beta-3</version>
<dependencies>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.2-FINAL</version>
<scope>compile</scope>
</dependency>
</dependencies>
<configuration>
<driver>oracle.jdbc.driver.OracleDriver</driver>
<url>jdbc:oracle:thin:@[dbserver]:[port]:[dbname]</url>
<username>username</username>
<password>password</password>
</configuration>
<!--
<executions>
<execution>
<phase></phase>
<goals>
<goal> </goal>
</goals>
</execution>
</executions>
-->
</plugin>
</plugins>
</build>
</project>
その上で、
$ mvn dbunit:export -Dschema=[schemaname] -Dformat=xls -Ddest=/dbunit/export.xls
のように実行する。
上記の場合はExcel形式でスキーマ名をしている。Oracleの場合スキーマ名を明示的に記述しなければいけないので注意。また、出力フォーマットをExcel形式(-Dformat=xls で指定)しても出力ファイル名の拡張子まで変更されなので、ファイル名も明示している。
dbunit-maven-pluginでは他にもDB関係の操作(もちろんインポートも)が提供されているので公式サイトを見てみるといいだろう。
mavenのPhaseに組み込むこともできるので、compileの度にDBへCLEAN INSERTの自動実行も可能となる。
# 実際に行うかは別。
[Java][maven][DB]DBをmavenでエクスポート More ログイン