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

相關文章
相關標籤/搜索