1. 程式人生 > >Spring boot JPA 用自定義主鍵策略 生成自定義主鍵ID

Spring boot JPA 用自定義主鍵策略 生成自定義主鍵ID

最近學習Spring boot 處理資料庫主鍵時JPA
 1 package javax.persistence;
 2 
 3 public enum GenerationType {
 4     TABLE,
 5     SEQUENCE,
 6     IDENTITY,
 7     AUTO;
 8 
 9     private GenerationType() {
10     }
11 }
GenerationType原始碼

從原始碼中可以看出JPA提供的四種標準主鍵策略TABLE,SEQUENCE,IDENTITY,AUTO

TABLE:使用一個特定的資料庫表格來儲存主鍵。

SEQUENCE:根據底層資料庫的序列來生成主鍵,條件是資料庫支援序列。 這個值要與generator一起使用,generator 指定生成主鍵使用的生成器(可能是orcale中自己編寫的序列)。

IDENTITY:主鍵由資料庫自動生成(主要是支援自動增長的資料庫,如mysql)

AUTO:主鍵由程式控制,也是GenerationType的預設值。

下面是具體程式碼

1.在實體getId()添加註解

1 @Id
2     @GeneratedValue(strategy = GenerationType.AUTO, generator = "custom-id") //
3 @GenericGenerator(name = "custom-id", strategy = "com.muyuer.springdemo.core.CustomIDGenerator") 4 @Column(name = "user_id") 5 public Long getUserId() { 6 return userId; 7 }
Entity添加註解

注意:GeneratedValue中的generator要與GenericGenerator中的name相等 上面程式碼中是"custom-id"

 2.新增自定義ID生成類

 1 package com.muyuer.springdemo.core;
 2 
 3 import com.muyuer.springdemo.utils.SnowflakeIdHelper;
 4 import org.hibernate.MappingException;
 5 import org.hibernate.engine.spi.SharedSessionContractImplementor;
 6 import org.hibernate.id.IdentityGenerator;
 7 import java.io.Serializable;
 8 
 9 /**
10  * 自定義ID生成器
11  * @author muyuer [email protected]
12  * @version 1.0
13  * @date 2018-12-08 15:42
14  */
15 public class CustomIDGenerator extends IdentityGenerator {
16     @Override
17     public Serializable generate(SharedSessionContractImplementor session, Object object) throws MappingException {
18         Object id =  SnowflakeIdHelper.getId();
19         if (id != null) {
20             return (Serializable) id;
21         }
22         return super.generate(session, object);
23     }
24 }
自定義ID生成器

這裡Override了generate方法通過SnowflakeIdHelper.getId();返回了自定義的ID。

注意:我測試的ID是Long型別所以這裡繼承的是IdentityGenerator類,如果ID為String型別的話應該繼承 UUIDGenerator 或者 UUIDGenerator