简体   繁体   English

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

[英]How to handle UUID as primary keys with OrmLite and Postgres?

I would like to have UUID as primary keys on a Postgres 9.4 database with OrmLite 5.0. 我想在OrmLite 5.0的Postgres 9.4数据库中使用UUID作为主键。

The table look like: 表格如下:

CREATE TABLE "test"(
    "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    "text" TEXT
)

With the associated POJO: 使用相关的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;
    }
}

I create my object with: 我创建我的对象:

Test t = new Test();
t.setText( "testing" );

myDao.create( t );

But I have the following error: 但是我有以下错误:

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.

Alright, the doc says that OrmLite generates an UUID before creating the object (thanks to generatedId ), and given that it tries to insert it as VARCHAR, it fails. 好吧,文档说OrmLite在创建对象之前生成一个UUID(感谢generatedId ),并且假设它尝试将其作为VARCHAR插入,它就会失败。 But I don't want my app to be able to alter the IDs, so I make the field read-only: 但我不希望我的应用程序能够更改ID,因此我将该字段设为只读:

@DatabaseField( generatedId = true, dataType = DataType.UUID_NATIVE, readOnly = true )

Great, the insert works but the ID set to the object is not the ID generated from the database (it's the OrmLite generated ID). 很好,插入工作但是设置到对象的ID不是从数据库生成的ID(它是OrmLite生成的ID)。

How can I make it work? 我怎样才能使它工作?

Note that I need to be able to write in native Postgres UUID fields with OrmLite since I will have UUID foreign keys and OrmLite will have to handle them. 请注意,我需要能够使用OrmLite 在本机Postgres UUID字段中编写,因为我将拥有UUID外键,OrmLite将必须处理它们。

You already have all the definitions in the database. 您已经拥有数据库中的所有定义。 If the ORM does not provide the ID it will be generated properly. 如果ORM未提供ID,则将正确生成。 So, simply preventing the ORM from creating it's own ID should work just fine. 因此,简单地阻止ORM创建自己的ID应该可以正常工作。

Something like that might help: 这样的事情可能会有所帮助:

@DatabaseField( dataType = DataType.UUID_NATIVE, readOnly = true )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM