如何使用OrmLite和Postgres处理UUID作为主键?

3
我希望在使用OrmLite 5.0的Postgres 9.4数据库上,将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字段中编写。
1个回答

1
你已经在数据库中拥有所有的定义。如果ORM没有提供ID,它将被正确生成。因此,只需防止ORM创建自己的ID即可正常工作。
类似以下内容可能会有所帮助:
@DatabaseField( dataType = DataType.UUID_NATIVE, readOnly = true )

它的工作结果与预期不符,因为没有generatedId标志,在插入后,创建的对象上的ID字段不会自动填充。此外,我认为OrmLite在不知道对象上哪个字段是关键字的情况下无法正确处理外键(而我需要外键管理)。 - Val
此外,我需要OrmLite能够写入UUID Postgres字段。 - Val

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接