Pgsql 使用UUID作主键

数据库生成主键的几种策略(前言)

这里能够参考:基于按annotation的hibernate主键生成策略sql

使用UUID作主键

两种方式:数据库

  • 使用Hibernate 提供的Type 方式(建议方式)session

    下一篇博客更深刻看一下自定义Typeapp

@Id
@Column(name = "customer_id")
@org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType")
private UUID id;


若是须要自动生成uuid,添加下面两个Annotation:

@GeneratedValue( generator = "uuid" )
@GenericGenerator(
            name = "uuid",
            strategy = "org.hibernate.id.UUIDGenerator",
            parameters = {
                    @Parameter(
                            name = "uuid_gen_strategy_class",
                            value = "org.hibernate.id.uuid.CustomVersionOneStrategy"
                    )
            }
    )
  • 使用Converter (自定义属性转换器)
//定义 converter
@Converter
public class UuidConverter implements AttributeConverter<UUID, Object> {
    @Override
    public Object convertToDatabaseColumn(UUID uuid) {
        PGobject object = new PGobject();
        object.setType("uuid");
        try {
            if (uuid == null) {
                object.setValue(null);
            } else {
                object.setValue(uuid.toString());
            }
        } catch (SQLException e) {
            throw new IllegalArgumentException("Error when creating Postgres uuid", e);
        }
        return object;
    }

    @Override
    public UUID convertToEntityAttribute(Object dbData) {
        return (UUID) dbData;
    }
}

// 使用
@Entity(name = "Event")
public static class Event {

    @Id
    @Convert(converter = UuidConverter.class)
    private UUID id;

    //Getters and setters are omitted for brevity

}

更多讨论: 为何不使用 String id ,而后将UUID 转换成 String 在get 和 set 方法中,这里有一些性能的问题,还待深刻理解? (pgsql 支持uuid 类型)ide

The PostgreSQL JDBC driver has chosen an unfortunately way to represent non-JDBC-standard type codes. They simply map all of them to Types.OTHER. Long story short, you need to enable a special Hibernate type mapping for handling UUID mappings (to columns of the postgres-specific uuid datatype):post

自定义主键生成策略

继承自IdentifierGenerator,这里使用org.bson.types.ObjectId作主键

public class StringIdGenerator implements IdentifierGenerator {

    public StringIdGenerator(){}

    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        return ObjectId.get().toString();
    }
}

使用:

@Id
    @Column(name = "id")
    @GeneratedValue(generator = "bson-id")
    @GenericGenerator(
            name = "bson-id",
            strategy = "com.social.credits.data.generator.StringIdGenerator"
    )
    private String id;

更多的细节(定义参数等)请自行查看文档,这里给个入门。

参考:性能

Persisting UUID in PostgreSQL using JPAui

UUID Primary Keys in PostgreSQLhibernate

相关文章
相关标签/搜索