2012-02-19 61 views
1

我想使用HSQLDB作爲嵌入式數據庫,但無法將其自動增量到自動增量使用HSQLDB自動增量(2.2.8)+ DDLUtils

據我所知,[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> 
+0

你使用什麼版本的HSQLDB? – 2012-02-19 00:12:46

+0

@EmmanuelBourg這是2.2.8,它可能是最新的。 – 2012-02-19 00:19:53

+0

這可能是問題的根源:http://stackoverflow.com/questions/4857730/how-to-fix-hsql-datasource-txm-where-identity-always-return-0 – 2012-02-19 18:29:55

回答

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

您用來創建表的SQL提供瞭解決方案:'一直生成爲身份'。我沒有提到我使用Apache DDLUnit自動使用XML生成表格。我將爲此尋求另一個框架。 – 2012-02-19 18:49:28

1

如果您使用ORM,他們將爲您執行標識列工作。 sormula使註解變得容易。有關示例,請參閱項目中的org.sormula.tests.identity包。定義

Row類:

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被包括在測試中。