Jam*_* P. 1 java ibatis hsqldb auto-increment 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>
Run Code Online (Sandbox Code Playgroud)
此外,这里是用于域类的 iBatis SQL 映射:
<insert id="insertUser" parameterClass="user">
<selectKey keyProperty="id" resultClass="int">
CALL IDENTITY()
</selectKey>
INSERT INTO USERS
( USERNAME, PASSWORD )
VALUES
( #username#, #password#)
</insert>
Run Code Online (Sandbox Code Playgroud)
这是一个打印出来的例子
0
1
2
Run Code Online (Sandbox Code Playgroud)
在我的机器上:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8478 次 |
| 最近记录: |