Skip to content

Commit

Permalink
snowflake id (#1517)
Browse files Browse the repository at this point in the history
Co-authored-by: Ben <[email protected]>
  • Loading branch information
liyin and Ben authored Jan 29, 2024
1 parent 68c6fc7 commit 8d5770c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
Expand Down Expand Up @@ -55,7 +56,8 @@
public class Alert {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "myid")
@GenericGenerator(name = "myid", strategy = "org.dromara.hertzbeat.common.util.SnowFlakeIdGenerator")
@Schema(title = "Alarm record entity primary key index ID",
description = "告警记录实体主键索引ID",
example = "87584674384", accessMode = READ_ONLY)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

Expand All @@ -30,7 +31,8 @@
public class History {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "myid")
@GenericGenerator(name = "myid", strategy = "org.dromara.hertzbeat.common.util.SnowFlakeIdGenerator")
@Schema(description = "指标数据历史实体主键索引ID", example = "87584674384", accessMode = READ_ONLY)
private Long id;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,35 @@

package org.dromara.hertzbeat.common.util;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentityGenerator;

import java.io.Serializable;

/**
* Snowflake Algorithm Generator Tool
*
*/
public class SnowFlakeIdGenerator {
public class SnowFlakeIdGenerator extends IdentityGenerator {

private static final SnowFlakeIdWorker ID_WORKER;

static {
ID_WORKER = new SnowFlakeIdWorker();
}

@Override
public Serializable generate(SharedSessionContractImplementor s, Object obj) throws HibernateException {
Serializable id = s.getEntityPersister(null, obj).getClassMetadata().getIdentifier(obj, s);

if (id != null && Long.valueOf(id.toString()) > 0) {
return id;
} else {
return SnowFlakeIdGenerator.generateId();
}
}

public static long generateId() {
return ID_WORKER.nextId();
}
Expand Down

0 comments on commit 8d5770c

Please sign in to comment.