Hibernate 和 JPA 注解方式自定义ID生成器

/**
 * Test.java
 * 实体类定义和配置
 */
package com.saving.ecm.resource.entity;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;


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



@XmlRootElement
@Entity
@Table(name = "test")
public class Test {
	@Id
	@GeneratedValue(generator = "idGenerator")
	@GenericGenerator(name = "idGenerator", strategy = "com.saving.ecm.resource.entity.IdGenerator",
	parameters = { @Parameter(name = "dataCenterID", value = "20") ,@Parameter(name = "idLength", value = "10")})
	private String code;


	@Column(name = "name", nullable = false, columnDefinition = "varchar(48) default '' comment '名字'")
	private String name;


	public String getCode() {
		return code;
	}


	public void setCode(String code) {
		this.code = code;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}




}



模拟自定义ID生成器

package com.saving.ecm.resource.entity;


import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.AbstractUUIDGenerator;
import org.hibernate.id.Configurable;
import org.hibernate.type.Type;



public class IdGenerator implements Configurable,IdentifierGenerator {


	public String dataCenterID;
	public String idLength;


	public void configure(Type type, Properties params, Dialect d) {
		this.dataCenterID = params.getProperty("dataCenterID");
		this.idLength = params.getProperty("idLength");
	}


	public Serializable generate(SessionImplementor session, Object obj) {
		return dataCenterID + idLength;
	}


}






展开阅读全文

没有更多推荐了,返回首页