hibernate中自定义主键(集群)

本文介绍了一种自定义的Hibernate主键生成器实现,该生成器支持使用Long类型作为主键,并能自动递增,同时具备在集群环境下运行的能力。通过具体的Java代码示例展示了如何创建和配置该主键生成器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在HIBERNATE中,identity ,sequence ,native 是数据局提供的主键生成方式,往往也不是我们需要,而且在程序跨数据库方面也体现出不足.还有基于算法的生成方式生成出来的主键基本都是字符串的.

  我们现在需要一种生成方式:使用Long作为主键类型,需要自动增,支持集群.那么我们需要自定义一个我们的主键生成器才能实现了.

 主键生成器代码 类:

     package com.ta.jiang;
  
  import java.io.Serializable;
  
  import java.sql.Connection;
  
  import java.sql.PreparedStatement;
  
  import java.sql.ResultSet;
  
  import java.sql.SQLException;
  
  import java.util.Properties;
  
  import org.apache.commons.logging.Log;
  
  import org.apache.commons.logging.LogFactory;
  
  import org.hibernate.HibernateException;
  
  import org.hibernate.MappingException;
  
  import org.hibernate.dialect.Dialect;
  
  import org.hibernate.engine.SessionImplementor;
  
  import org.hibernate.id.Configurable;
  
  import org.hibernate.id.IdentifierGenerator;
  
  import org.hibernate.id.PersistentIdentifierGenerator;
  
  import org.hibernate.type.Type;
  
  public class IncrementGenerator implements IdentifierGenerator, Configurable {
  
  private static final Log log = LogFactory.getLog(IncrementGenerator.class);
  
  private Long next;
  
  private String sql;
  
  public Serializable generate(SessionImplementor session, Object object)
  
  throws HibernateException {
  
  if (sql!=null) {
  
   getNext( session.connection() );
  
  }
  
  return 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);
  
  sql = "select max("+column +") from " + ( schema==null ? table : schema + '.' + table );
  
  log.info(sql);
  
  }
  
   private void getNext(Connection conn) throws HibernateException {
  
  try {
  
  PreparedStatement st = conn.prepareStatement(sql);
  
  ResultSet rs = st.executeQuery();
  
  if ( rs.next() ) {
  
  next = rs.getLong(1) + 1;
  
  }
  
  else {
  
  next = 1l;
  
  }
  
  }catch(SQLException e)
  
  {
  
  throw new HibernateException(e);
  
  }
  
  finally {
  
  try{
  
  conn.close();
  
  }catch(SQLException e)
  
  {
  
  throw new HibernateException(e);
  
  }
  
  }
  
  }
  
  }

  代码二:

  Hibernate 配置文件:

  <id name="id" type="long" column="id" >
  
  <generator class="com.ta.jiang.IncrementGenerator" />
  
  </id>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值