数据库生成主键的几种策略(前言)
这里可以参考:基于按annotation的hibernate主键生成策略
使用UUID做主键
两种方式:
@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 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 类型)
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):
自定义主键生成策略
继承自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; 更多的细节(定义参数等)请自行查看文档,这里给个入门。
参考: