天天看點

JPA中使用 @GenericGenerator 自定義方式 生成 主鍵 ID

一、官網資料

1、文檔位址:https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators-GenericGenerator

2、文檔說明:需要實作 org.hibernate.id.IdentifierGenerator 這個接口

@GenericGenerator allows integration of any Hibernate org.hibernate.id.IdentifierGenerator implementation, 
including any of the specific ones discussed here and any custom ones.
           

3、官網中的案例(寫的很詳細,直接對這個類進行改造):

JPA中使用 @GenericGenerator 自定義方式 生成 主鍵 ID

二、改造一下官網的案例 

1、實體類:

@Data
@Entity
@Table(name = OrderTable.TABLE_NAME,
    indexes = {
        @Index(name = "id", columnList = "id", unique = true)
    })
@AllArgsConstructor
@NoArgsConstructor
@Builder
@EntityListeners(AuditingEntityListener.class)
public class OrderTable {

  public static final String TABLE_NAME = "order_table";

  /**
   * 使用 snowflake : 雪花算法。
   */
  @Id
  @GeneratedValue(generator = "orderIdGenerator",
      strategy = GenerationType.SEQUENCE)
  @GenericGenerator(
      name = "orderIdGenerator",
      strategy = "com.wangyk.sharding.config.OrderIdGeneratorConfig"
  )
  private Long id;

  @Column(columnDefinition = "BIGINT(20) COMMENT '訂單Id'")
  private Long orderId;

  @Column(columnDefinition = "BIGINT(20) COMMENT '使用者Id'")
  private Long userId;

  @Column(columnDefinition = "VARCHAR(255) COMMENT '訂單備注'")
  private String remark;

  @Column
  @CreatedDate
  private Date creation;

  @Column
  @LastModifiedDate
  private Date modification;
}
           

2.實作類

@Slf4j
public class OrderIdGeneratorConfig implements IdentifierGenerator {

  @Override
  public Serializable generate(SharedSessionContractImplementor session, Object object)
      throws HibernateException {
    /**
     * 擷取容器中的 Bean
     */
    SnowflakeIdWorker snowflakeIdWorker = SpringUtil.getBean(SnowflakeIdWorker.class);
    long id = snowflakeIdWorker.nextId();
    log.info("id -> [{}]", id);
    return id;
  }
}
           

3.自定義生成主鍵ID成功

JPA中使用 @GenericGenerator 自定義方式 生成 主鍵 ID