jpa自定义id生成策略

在使用的JPA的时候,通常会在实体类里面为主键id配置id的生成策略,比如下面这样的,生成UUID作为主键

@Id
@GeneratedValue(generator="sys_uid")
@GenericGenerator(name="sys_uid", strategy="uuid")
private String id;

但是,这个有时候不能完全满足我们的需要。我们需要一个自定义的id,比如:
用户表id

USER-f14c1663ba4c4317b6b6b8857d31c915

角色表id

ROLE-f14c1663ba4c4317b6b6b8857d31c915

自定义id生成策略

首先需要写一个类实现ConfigurableIdentifierGenerator

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

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;

/**
 * 	自定义id生成
 * @author hll
 *
 */
public class CustomGenerationId implements Configurable,IdentifierGenerator {
	
	/**
	 * id前缀
	 */
	private String idPrefix;
	
	public CustomGenerationId() {};

	@Override
	public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
		// TODO Auto-generated method stub
		return getId();
	}

	@Override
	public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
		// TODO Auto-generated method stub
		this.idPrefix = params.getProperty("idPrefix"); //	实体类中@Parameter注解,根据键值获取value
	}
	
	/**
	 * 	该方法需要是线程安全的
	 * @return
	 */
	public String getId() {
		synchronized (CustomGenerationId.class) {
			String uuid = UUID.randomUUID().toString().replace("-", "");
			return idPrefix + "-" + uuid;
		}
	}
}

实体类

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name="users")
public class User implements Serializable {

	@Id
	@GeneratedValue(generator="customGenerationId")
	@GenericGenerator(name="customGenerationId", strategy="com.hll.utils.CustomGenerationId",
				parameters = {@Parameter(name="idPrefix", value="USER")} )
	private String id;
		
	//省略....
}

猜你喜欢

转载自blog.csdn.net/sinat_33151213/article/details/91979121