标签:hibernate orm 框架 java 主键生成器
increment
对long、int、short的数据列生成自动增长主键。用于数据库中未把表格主键设置为自增,而又想表格主键自增时
<id name="id" column="id"> <generator class="sequence"> <!-- 数据库中创建系列userTb_seq --> <param name="sequence">userTb_seq</param> </generator> </id>
<id name="id" column="id"> <generator class="assigned" /> </id>
<id name="id" type="long" column="ID"> <generator class="hilo"> <param name="table">hi_value</param> <param name="column">next_value</param> <param name="max_lo">100</param> </generator> </id>
通过数据库触发器选择某个唯一主键的行,并返回其主键值作为标识属性值
自定义主键生成器
主键生成器必须实现 net.sf.hibernate.id.IdentifierGenerator 接口
主键生成类MyIdentifierGenerator
public class MyIncrementGenerator implements IdentifierGenerator, Configurable{ private static final Log log = LogFactory.getLog(MyIncrementGenerator.class); private long next; private String sql; public synchronized Serializable generate(SessionImplementor session, Object object) throws SQLException, HibernateException { if (sql!=null) { //获得下一个主键的编号,可以自己定义 getNext(session.connection()); } return String.valueOf(next); } public void configure(Type type, Properties params, Dialect d)throws MappingException{ String table = params.getProperty("table"); if (table==null) table = params.getProperty(PersistentIdentifierGenerator.TABLE); String column = params.getProperty("column"); if (column==null) column = params.getProperty(PersistentIdentifierGenerator.PK); String schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA); returnClass = type.getReturnedClass(); sql = "select max(to_number(" + column + ")) from " + ( schema==null ? table : schema + '.' + table ); } private void getNext(Connection conn)throws SQLException { PreparedStatement st = conn.prepareStatement(sql); ResultSet rs = null; try { rs = st.executeQuery(); if ( rs.next()) { next = rs.getLong(1) + 1; if ( rs.wasNull() ) next = 1; } else { next = 1; } sql=null; log.debug("first free id: " + next); } finally { if (rs!=null) rs.close(); st.close(); } }
然后再需要使用自定义的主键生成器构造主键的数据库对象所对应的.XML文件中可以这样写:
<id name="uniqueid" column="UNIQUEID" type="string"> <generator class="com.core.persistence.MyIncrementGenerator"/> </id>
标签:hibernate orm 框架 java 主键生成器
原文地址:http://blog.csdn.net/hekewangzi/article/details/41379925