有很多种策略,比如sqlserver,mysql有autoincrement类型
oracle有sequence
最通用的方法就是用一个类来做主键生成器,这样可以做到数据库无关
package ejb.counter;import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.ejb.*;
import cn.com.aheadsoft.app.ServiceLocator;
import cn.com.aheadsoft.app.ServiceLocatorException;public class CounterBean implements SessionBean {
  SessionContext sessionContext;
  public void ejbCreate() throws CreateException {
    /**@todo Complete this method*/
  }
  public void ejbRemove() {
    /**@todo Complete this method*/
  }
  public void ejbActivate() {
    /**@todo Complete this method*/
  }
  public void ejbPassivate() {
    /**@todo Complete this method*/
  }
  public void setSessionContext(SessionContext sessionContext) {
    this.sessionContext = sessionContext;
  }
  public java.math.BigDecimal getNextValue() throws CounterException {
    BigDecimal valueReturned=new BigDecimal(0);
    Connection con=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    try{
     //将计数器加一
     String sql="update counter set value=value+1";
     ServiceLocator serviceLocator=ServiceLocator.getInstance();
     con=serviceLocator.getConnection();
     ps=con.prepareStatement(sql);
     ps.execute();
     //返回记数器的值
     sql="select value from counter";
     ps=con.prepareStatement(sql);
     rs=ps.executeQuery();
     if(rs.next()){
       valueReturned=rs.getBigDecimal("value");
     }else{
       //初始化计数器
       sql="insert into Counter (value) values (0)";
       ps=con.prepareStatement(sql);
       ps.execute();
       con.commit();
     }
   }catch(ServiceLocatorException e){
     throw new CounterException("数据库连接失败");
   }catch(SQLException e){
     throw new CounterException("数据库操作失败");
   }finally{
     try{
       if(ps!=null){
         ps.close();
       }
       if(con!=null){
         con.close();
       }
     }catch(Exception e){
       e.printStackTrace();
     }
   }
   return valueReturned;
  }
}

解决方案 »

  1.   

    看看SJEP产品,你这个问题可以轻松解决,属于SJEP里面的数据库自动给
    字段赋值的情况,也就是增加记录时字段是有缺省值的情况。
      

  2.   

    如果用weblogic:Weblogic只支持MS-SQLServer和Oracle的字段自增,首先在数据库中设好数据库自增管理,然后在weblogic-cmp-rdbms-jar.xml中的<weblogic-rdbms-bean>项的最后添加:
    <automatic-key-generation> <generator-type>SQL_SERVER</generator-type>
    </automatic-key-generation>
    当通过实体Bean在数据库中插入数据时,只要在EntityBean的create()中的自增主键随便给一个参数值就行了。
    Oracle则用Oracle替换SQL_SERVER。
      

  3.   

    最好用JB生成,里面有选项Weblogic.property里有选项key cache填一个值就可以了,很简单,建议设大一些
      

  4.   

    Different App server has its owner ways to deal with it. You need to look at App server guide about EJB for this section.