1

HSQLDB を組み込みデータベースとして使用したいのですが、自動インクリメントに問題があります。

私が理解している限り[CALL] IDENTITY()、最後の主キー値を取得するために使用できます。ただし、iBatis と HSQLDB の両方を使用した実験では、DatabaseManagerSwing常に 0 の値が返されます。

自動インクリメントを HSQLDB で動作させるにはどうすればよいですか?

編集:

テーブルの自動生成にDDLUtilsを使用しているとは言いませんでした。以下はHSQLDB に適していません。

<?xml version="1.0"?>
<!DOCTYPE database SYSTEM "http://db.apache.org/torque/dtd/database.dtd">

<database name="testdb">

    <table name="users">
        <!-- using autoincrement attribute below causes
        "primary key already exists" exception -->
        <column name="id" type="INTEGER" primaryKey="true" />
        <column name="username" type="VARCHAR" size="30" />
        <column name="password" type="VARCHAR" size="100" />
    </table>

</database>

また、ドメイン クラスに使用される iBatis SQL マップは次のとおりです。

<insert id="insertUser" parameterClass="user">
    <selectKey keyProperty="id" resultClass="int">
        CALL IDENTITY()
    </selectKey>
INSERT INTO USERS
( USERNAME, PASSWORD ) 
VALUES
( #username#, #password#)       
</insert>
4

2 に答える 2

5

これが印刷される例です

0
1
2

私のマシンで:

import java.io.File;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Date;

public class Test {

  public static void main(String[] args) throws Exception {

    File dbDir = new File("/tmp/identity_test"); 
    String connectionTemplate = "jdbc:hsqldb:file:%s/test";
    String connStr = String.format(connectionTemplate, dbDir);
    Connection connection = DriverManager.getConnection(connStr, "", "");
    Statement s = connection.createStatement();
    s.execute("CREATE TABLE test (id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, s VARCHAR(10))");
    PreparedStatement psInsert = connection.prepareStatement("INSERT INTO test (s) VALUES (?)");
    for (int i = 0; i < 3; i++) {
      psInsert.setString(1, "hello");
      psInsert.executeUpdate();
      PreparedStatement psIdentity = connection.prepareStatement("CALL IDENTITY()");
      ResultSet result = psIdentity.executeQuery();
      result.next();
      int identity = result.getInt(1);
      result.close();
      System.out.println(identity);
    }
    connection.close();
  }
}
于 2012-02-19T00:57:39.253 に答える
1

ORM を使用すると、ID 列の作業が実行されます。sormulaはアノテーションで簡単にできます。例については、プロジェクト内の org.sormula.tests.identity パッケージを参照してください。

行クラスの定義:

public class IdentityTest
{
    @Column(identity=true)
    int id;
    ...

org.sormula.identity.tests.InsertTest から:

 IdentityTest row = new IdentityTest(-1, "Insert one");
 assert getTable().insert(row) == 1 : "insert one failed";
 assert row.getId() > 0 : "indentity column was not generated";

HSQLDB はテストに含まれています。

于 2012-02-19T15:30:39.303 に答える