实体对象定义如下:
@Data
@Entity
@Table(name = "sys_user")
public class UserDO {
/** 用户id */
@Id
@GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
@GeneratedValue(generator = "uuid")
@Column(length = 36, nullable = false)
private String userId;
....
}
调用jpa的save方法,即使手动设置了id,手动设置的这个id也会被覆盖。
要求:当用户手动设置了id,以用户设置的id为准,否则使用uuid
解决方案如下:使用自定义id生成策略,判断id非空
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.UUIDGenerator;
import javax.persistence.Id;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 自定义uuid生成策略, 扩展 {@link org.hibernate.id.UUIDGenerator}
* 当用户设置了id,以用户设置的id为主,为空则生成uuid
* {@link javax.persistence.Id} 注解的字段只处理第一个
*
* @author qiudw
* @date 7/7/2023
*/
@Slf4j
public class CustomerUuidGenerator extends UUIDGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) {
Class<?> clazz = obj.getClass();
log.debug("generate id class: {}", clazz.getName());
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
Id idAnnotation = field.getAnnotation(Id.class);
if (idAnnotation == null) {
continue;
}
String fieldName = field.getName();
log.debug("field name: {}", fieldName);
String getMethodName = generateGetMethodName(fieldName);
log.debug("get method name: {}", getMethodName);
Method declaredMethod = clazz.getDeclaredMethod(getMethodName);
String idValue = (String) declaredMethod.invoke(obj);
if (StrUtil.isNotBlank(idValue)) {
log.debug("use set value: {}", idValue);
return idValue;
}
}
} catch (NoSuchMethodException e) {
log.error("no such method", e);
} catch (InvocationTargetException | IllegalAccessException e) {
log.error("invoke exception", e);
}
return super.generate(session, obj);
}
/**
* 生成get和set的方法名称
* type + 首字母大写(fieldName)
*
* @param fieldName userId
* @return type = set, fieldName = userId, 返回 setUserId
*/
private String generateGetMethodName(String fieldName) {
return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
}
}
实体对象使用自定的策略
@Data
@Entity
@Table(name = "sys_user")
public class UserDO {
/** 用户id */
@Id
@GenericGenerator(name = "uuid", strategy = "com.user.CustomerUuidGenerator")
@GeneratedValue(generator = "uuid")
@Column(length = 36, nullable = false)
private String userId;
....
}
现在可以手动设置id了
不设置则自动生成uuid