使用HSQLDB(2.2.8)+ DDLUtils自动增量

时间:2012-02-19 00:02:21

标签: java hsqldb auto-increment ibatis ddlutils

我想将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>

2 个答案:

答案 0 :(得分:4)

这是一个打印出来的例子

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();
  }
}

答案 1 :(得分:1)

如果您使用ORM,他们将为您执行标识列工作。使用注释可以轻松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包含在测试中。