160727、自定义hibernate主键生成策略生成字符串+数字自增长
需求:需要自增长注解如MyId0001、MyId0002、MyId0003 实现:实现这个接口org.hibernate.id.IdentifierGenerator 一、MyIdGenerator.java(测试用,实际项目中获取链接等可以改变) import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.lang.StringUtils; import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; import org.hibernate.id.IdentifierGenerator; public class MyIdGenerator implements IdentifierGenerator{ @Override public Serializable generate(SessionImplementor session, Object object) throws HibernateException { String prefix = "MyId"; Connection connection = session.connection(); try { PreparedStatement ps = connection .prepareStatement("SELECT nextval ('seq_id') as nextval"); ResultSet rs = ps.executeQuery(); if (rs.next()) { int id = rs.getInt("nextval"); String code = prefix + StringUtils.leftPad("" + id,3, '0'); log.debug("Generated Stock Code: " + code); return code; } } catch (SQLException e) { log.error(null, e); throw new HibernateException( "Unable to generate Stock Code Sequence"); } return null; } } 二、配置hibernate主键生成策略 基于配置文件的hibernate(TestHibernateIdentifier.xml) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.fire.front.entity"> <class name="TestHibernateIdentifier" table="test_hibernate_identifier" dynamic-update="true"> <meta attribute="sync-DAO">false</meta> <cache usage="read-write"/> <id name="id" type="string" column="id"> <generator class="com.gwold.common.util.MyIdGenerator"/> </id> <property name="name" type="string" column="name" length="40"/> </class> </hibernate-mapping> 基于注解的方式 import java.io.Serializable; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; public class TestHibernateIdentifier implements Serializable{ @Id @GenericGenerator(name="seq_id", strategy="com.gwold.common.util.MyIdGenerator") @GeneratedValue(generator="seq_id") @Column(name = "id", unique = true, nullable = false, length = 20) private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }