hibernate自定义主键

hibernate自定义主键要继承TableGenerator
public class IdGenerator extends TableGenerator
要实现generate方法:
public synchronized Serializable generate(SessionImplementor session,
   Object obj) throws HibernateException, HibernateException {
//我们一般用long型,所以我这里返回一个long型字段,当然不局限于long型,String或其它类型都可以.
}
代码如下:
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.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.TableGenerator;
import org.hibernate.type.Type;

import cn.com.s520.leopard.cache.CommonDefine;


public class IdGenerator extends TableGenerator {
 static final Logger logger = Logger.getLogger(IdGenerator.class.getName());
 private String tableName;
 public static long idValue; //数据库存在最大ID记录
 
 public void configure(Type type, Properties params, Dialect d) {
  super.configure(type, params, d);
  tableName = (params.getProperty("tableName") == null ? "leopard" : params
    .getProperty("tableName"));
 }

 public synchronized Serializable generate(SessionImplementor session,
   Object obj) throws HibernateException, HibernateException {
  
  if (idValue > 0) {
   long _idValue =idValue;
   idValue =0;
   return _idValue;
  }
  

  Connection conn = session.getBatcher().openConnection();
  long nextNo = 1;

  String SQL_GETNO = "select nextIntNo from sys_id_serial where tableName = ?";
  String SQL_INSERT = "INSERT INTO sys_id_serial (tableName,nextIntNo) VALUES(?,?)";
  String SQL_GETNO_UPDATE = "UPDATE sys_id_serial set nextIntNo=? WHERE tableName=?";
  PreparedStatement pstmt = null;
  try {
   pstmt = conn.prepareStatement(SQL_GETNO);
   pstmt.setString(1, tableName);
   ResultSet re = pstmt.executeQuery();
   if (re.next()) { //数据库存在最大ID记录
    nextNo = re.getLong(1) + 1L;
    logger.info("nextNo::"+nextNo);
    re.close();
    pstmt = conn.prepareStatement(SQL_GETNO_UPDATE);
    pstmt.setLong(1, nextNo);
    pstmt.setString(2, tableName);
    pstmt.executeUpdate();
    logger.info("SQL_GETNO_UPDATE::"+tableName);
   }
   else {//数据库不存在最大ID记录 就添加一个初始值
    nextNo = CommonDefine.synchronousID;
    pstmt = conn.prepareStatement(SQL_INSERT);
    pstmt.setString(1, tableName);
    
    //TODO 在线激活方式
    pstmt.setLong(2, nextNo); //服务器端设置为1开始
    pstmt.executeUpdate();
    
   }
  }catch (SQLException e) {
   session.getBatcher().abortBatch(e);
   e.printStackTrace();
  }finally{
   if(conn!=null){
    try {
     session.getBatcher().closeConnection(conn);
     conn.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
   
  }
  logger.info("nextNo::"+nextNo);
  return nextNo;
 }

 public static long getIdValue() {
  return idValue;
 }

 public static void setIdValue(long idValue) {
  IdGenerator.idValue = idValue;
 }
}
 

你可能感兴趣的:(java,apache,sql,Hibernate,log4j)