そのためにWareworkを使用しています。これは大きな JAR ですが、あなたが探しているものを実行すると思います。それがどのように機能するかをお見せします:
1-プロジェクトのソース フォルダーに次のディレクトリ構造を作成します。
/META-INF/system/statement/sql
2- " /META-INF/system " ディレクトリに、" pool-service.xml " という名前のファイルを次の内容で作成します。
<?xml version="1.0" encoding="UTF-8"?>
<proxy-service xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://repository.warework.com/xsd/proxyservice-1.0.0.xsd">
<clients>
<client name="c3p0-client" connector="com.warework.service.pool.client.connector.C3P0Connector">
<parameter name="driver-class" value="com.mysql.jdbc.Driver" />
<parameter name="jdbc-url" value="jdbc:mysql://host:port/database-name" />
<parameter name="user" value="the-user-name" />
<parameter name="password" value="the-password" />
<parameter name="connect-on-create" value="true" />
</client>
</clients>
</proxy-service>
このファイルで、パラメーターの値を、データベースに接続するために必要な値に置き換えます。" connect-on-create " を " true " に保ちます。
3- " /META-INF/system/statement/sql " ディレクトリに .sql スクリプトを記述します。次のようなSELECTステートメントを記述できます(ファイルごとに 1 つのステートメント)。
検索-user.sql
SELECT * FROM HOME_USERS A WHERE A.ID = ${USER_ID}
および次のようなUPDATEステートメント (ファイルごとに 1 つまたは複数のステートメント):
create-user.sql
INSERT INTO HOME_USERS (ID, NAME) VALUES (${USER_ID}, ${USER_NAME});
INSERT INTO ACTIVE_USERS (ID) VALUES (${USER_ID});
4-データベースに接続するには、次の手順を実行します。
// "Test.class" must be any class of your project (the same project where /META-INF/system directory exists).
// Do not change "full" and "relational-database" strings.
// If you change "system" for "test", then the directory will be /META-INF/test.
RDBMSView ddbb = (RDBMSView) ScopeFactory.createTemplate(Test.class, "full", "system").getObject("relational-database");
// Connect with the database.
ddbb.connect();
5-次のように .sql ファイルからSELECTステートメントを実行します。
// Values for variables in the SELECT statement.
Hashtable values = new Hashtable();
// Set variables to filter the query.
values.put("USER_ID", new Integer(8375));
// Read '/META-INF/system/statement/sql/find-user.sql', replace variables and run.
// -1 values are for pagination (first -1 is the page, second -1 is the max rows per page).
ResultSet result = (ResultSet) ddbb.executeQueryByName("find-user", values, -1, -1);
6-次のように .sql ファイルからUPDATEステートメントを実行します。
// Values for variables in the UPDATE statements.
Hashtable values = new Hashtable();
// Set variables for the update statement.
values.put("USER_ID", new Integer(3));
values.put("USER_NAME", "Oompa Loompa");
// Read '/META-INF/system/statement/sql/create-user.sql', replace variables and run.
// ';' is the character that separates each statement.
ddbb.executeUpdateByName("create-user", values, new Character(';'));
RDBMSViewクラスは、これらのメソッドに加えて、接続/切断、コミット、ロールバックなどを提供します。また、String オブジェクトからステートメントを直接実行することもできます。