springBoot 集成hibernate自动建立表和,指定表id 为雪花id

集成hibernate和雪花id

1、添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>2.3.2.RELEASE</version>
    </dependency>
    
     <dependency>
         <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>5.5.7.Final</version>
     </dependency>

2、添加配置 指定数据源和hivernate 方言配置

     spring:
       datasource:
         driver-class-name: com.mysql.jdbc.Driver
         url: jdbc:mysql://127.0.0.1:3306/dh-home?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
         username: root
         password: root
       jpa:
         hibernate:
           ddl-auto: update
         show-sql: true
         database: mysql
         generate-ddl: true
         properties:
           hibernate:
             dialect: org.hibernate.dialect.MySQL5InnoDBDialect

3、实体添加@Entity

         @Entity
         @Table(name = Constants.SYS_+"user")
         @TableName(value = Constants.SYS_+"user")
         @Data
        public class User extends BaseEntity {
         @Column(columnDefinition = "varchar(255) comment '姓名' ")
         private String name;
     
         @Column(columnDefinition = "varchar(255) comment '密码' ")
         private String password;
     }

雪花id生成

1、指定id生成策略

@Id
@GenericGenerator(name = "snowFlakeIdGenerator", strategy = "com.ayou.shunfengche.config.SnowFlakeIdGenerator")
@GeneratedValue(generator = "snowFlakeIdGenerator")
@Column(name = "id", length=18)
private Long id;

2、添加雪花id生成类:

package com.ayou.shunfengche.config;

import javax.annotation.PostConstruct;

import org.hibernate.HibernateException;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 雪花算法
 */
@Component
public class SnowFlake implements ApplicationContextAware {
  private static final CoreMessageLogger LOG = CoreLogging.messageLogger(SnowFlake.class);

  private static ApplicationContext _applicationContext;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SnowFlake._applicationContext = applicationContext;
  }
  
  public static SnowFlake getBean() {
    return _applicationContext.getBean(SnowFlake.class);
  }
  
  /**
   * 起始的时间戳
   */
  private final long twepoch = 1557825652094L;

  /**
   * 每一部分占用的位数
   */
  private final long workerIdBits = 5L;
  private final long datacenterIdBits = 5L;
  private final long sequenceBits = 12L;

  /**
   * 每一部分的最大值
   */
  private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
  private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
  private final long maxSequence = -1L ^ (-1L << sequenceBits);

  /**
   * 每一部分向左的位移
   */
  private final long workerIdShift = sequenceBits;
  private final long datacenterIdShift = sequenceBits + workerIdBits;
  private final long timestampShift = sequenceBits + workerIdBits + datacenterIdBits;

  @Value("${snowflake.datacenter-id:1}")
  private long datacenterId; // 数据中心ID

  @Value("${snowflake.worker-id:0}")
  private long workerId; // 机器ID

  private long sequence = 0L; // 序列号
  private long lastTimestamp = -1L; // 上一次时间戳
  
  @PostConstruct
  public void init() {
    String msg;
    if (workerId > maxWorkerId || workerId < 0) {
      msg = String.format("worker Id can't be greater than %d or less than 0", maxWorkerId);
      LOG.unsuccessful(msg);
    }
    if (datacenterId > maxDatacenterId || datacenterId < 0) {
      msg = String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId);
      LOG.unsuccessful(msg);
    }
  }

  public Long nextIdString() {
    long id = nextId();
    
    return id;
  }
  
  public synchronized long nextId() {
    long timestamp = timeGen();
    if (timestamp < lastTimestamp) {
      throw new HibernateException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
    }
    if (timestamp == lastTimestamp) {
      sequence = (sequence + 1) & maxSequence;
      if (sequence == 0L) {
        timestamp = tilNextMillis();
      }
    } else {
      sequence = 0L;
    }
    lastTimestamp = timestamp;

    return (timestamp - twepoch) << timestampShift // 时间戳部分
        | datacenterId << datacenterIdShift // 数据中心部分
        | workerId << workerIdShift // 机器标识部分
        | sequence; // 序列号部分
  }

  private long tilNextMillis() {
    long timestamp = timeGen();
    while (timestamp <= lastTimestamp) {
      timestamp = timeGen();
    }
    return timestamp;
  }

  private long timeGen() {
    return System.currentTimeMillis();
  }

}
package com.ayou.shunfengche.config;

import java.io.Serializable;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

/**
 * JPA 雪花算法ID生成器
 */
public class SnowFlakeIdGenerator implements IdentifierGenerator, Configurable {

  @Override
  public Serializable generate(SharedSessionContractImplementor session, Object o) throws HibernateException {
    return SnowFlake.getBean().nextIdString();
  }

  @Override
  public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
  }
}

自此完成配置,调用mybaits-plus的save 方法生成如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot集成Hibernate可以实现方便的数据库操作。下面是一些步骤来实现集成: 1. 添加依赖:在项目的pom.xml文件中添加Spring BootHibernate的依赖。例如: ```xml <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> </dependencies> ``` 2. 配置数据源:在应用的配置文件(如application.properties或application.yml)中配置数据库连接信息。例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=username spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect ``` 3. 定义实体类:创建与数据库对应的实体类,并使用注解来定义实体类与的映射关系。例如: ```java @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // getters and setters } ``` 4. 创建Repository:创建一个继承自`JpaRepository`的接口,用于定义对实体类进行CRUD操作的方法。例如: ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { // 自定义查询方法 User findByName(String name); } ``` 5. 使用Hibernate进行数据库操作:在需要进行数据库操作的地方,通过注入Repository来使用Hibernate进行操作。例如: ```java @Service public class UserService { @Autowired private UserRepository userRepository; public User getUserByName(String name) { return userRepository.findByName(name); } // 其他业务逻辑方法 } ``` 这样,你就可以在Spring Boot使用Hibernate进行数据库操作了。注意,以上只是一个简单的示例,实际项目中可能需要更多的配置和细节处理。你可以根据自己的需求来进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值