我希望在使用OrmLite 5.0的Postgres 9.4数据库上,将UUID作为主键。
表格如下:
我用以下代码创建了我的对象:
但是我遇到了以下错误:
很好,插入操作已经成功了,但是对象设置的ID不是从数据库生成的ID(而是OrmLite生成的ID)。
我该怎么办?
请注意,由于我将使用UUID外键并且OrmLite必须处理它们,因此需要能够在本地Postgres UUID字段中编写。
表格如下:
CREATE TABLE "test"(
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"text" TEXT
)
使用相关的POJO:
package test;
import java.util.UUID;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable( tableName = "test" )
public class Test
{
@DatabaseField( generatedId = true, dataType = DataType.UUID_NATIVE )
private UUID id;
@DatabaseField
private String text;
public Test()
{}
public UUID getId()
{
return this.id;
}
public void setId( UUID id )
{
this.id = id;
}
public String getText()
{
return this.text;
}
public void setText( String text )
{
this.text = text;
}
}
我用以下代码创建了我的对象:
:
Test t = new Test();
t.setText( "testing" );
myDao.create( t );
但是我遇到了以下错误:
org.postgresql.util.PSQLException: ERROR: column "id" is of type uuid but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
好的,文档中提到OrmLite在创建对象之前生成UUID(感谢generatedId
),并且尝试将其作为VARCHAR插入,从而失败。但我不希望我的应用程序能够更改ID,因此我将该字段设置为只读:
@DatabaseField( generatedId = true, dataType = DataType.UUID_NATIVE, readOnly = true )
很好,插入操作已经成功了,但是对象设置的ID不是从数据库生成的ID(而是OrmLite生成的ID)。
我该怎么办?
请注意,由于我将使用UUID外键并且OrmLite必须处理它们,因此需要能够在本地Postgres UUID字段中编写。
generatedId
标志,在插入后,创建的对象上的ID字段不会自动填充。此外,我认为OrmLite在不知道对象上哪个字段是关键字的情况下无法正确处理外键(而我需要外键管理)。 - Val