Reputation: 46
I would like to have UUID as primary keys on a Postgres 9.4 database with OrmLite 5.0.
The table look like:
CREATE TABLE "test"(
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"text" TEXT
)
With the associated 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. But I don't want my app to be able to alter the IDs, so I make the field read-only:
@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).
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.
Upvotes: 3
Views: 855
Reputation: 3701
You already have all the definitions in the database. If the ORM does not provide the ID it will be generated properly. So, simply preventing the ORM from creating it's own ID should work just fine.
Something like that might help:
@DatabaseField( dataType = DataType.UUID_NATIVE, readOnly = true )
Upvotes: 1