兩種方法。一﹐象Oracle, DB2, MySQL這些流行數據庫都有Auto Increment或Auto Generated字段﹐這些字段用來做主鍵再合適不過了。你只要Insert一條記錄﹐主鍵值自動累加﹐永不重複。所以﹐你在ejbCreate()中先Insert一條新記錄﹐主鍵在Insert SQL中不寫﹐讓數據庫自己累加﹔然後﹐用一條Select語句將剛新記錄的主鍵值取出。二﹐自己編一套算法能夠生成GUID(Global Unique Identity)。GUID可理解成一隨機數﹐由于位數多﹐因此重複的概率極小﹐可被當作主鍵值。算法如下:   public static final String generateGUID(Object o) {
       StringBuffer tmpBuffer = new StringBuffer(16);
       if (hexServerIP == null) {
           InetAddress localInetAddress = null;
           try {
               // get the inet address
               localInetAddress = InetAddress.getLocalHost();
           }
           catch (java.net.UnknownHostException uhe) {
               System.err.println("AccountServicesUtil: Could not get the local IP address using InetAddress.getLocalHost()!");
               // todo: find better way to get around this...
               uhe.printStackTrace();
               return null;
           }
           byte serverIP[] = localInetAddress.getAddress();
           hexServerIP = hexFormat(getInt(serverIP), 8);
       }
       String hashcode = hexFormat(System.identityHashCode(o), 8);
       tmpBuffer.append(hexServerIP);
       tmpBuffer.append(hashcode);       long timeNow      = System.currentTimeMillis();
       int timeLow       = (int)timeNow & 0xFFFFFFFF;
       int node          = seeder.nextInt();       StringBuffer guid = new StringBuffer(32);
       guid.append(hexFormat(timeLow, 8));
       guid.append(tmpBuffer.toString());
       guid.append(hexFormat(node, 8));
       return guid.toString();
   }利用generateGUID(this)來生成主鍵值﹐然後在ejbCreate()裡和Insert語句一起插入記錄進數據庫。

解决方案 »

  1.   

    谢谢,我好像试过第一种方法在sql语句中不写主键,好像不行,提示主键不可为null,不知是否还要在哪设?
      

  2.   

    Weblogic只支持MS-SQLServer和Oracle的主键自增,主键类型必须为Integer或Long。先在数据库中设好自增,然后在weblogic-cmp-rdbms-jar.xml中的<weblogic-rdbms-bean>项的最后添加:
    <automatic-key-generation> <generator-type>SQL_SERVER</generator-type>
    </automatic-key-generation>
    当通过实体Bean在数据库中插入数据时,只要在EntityBean的create()中的自增主键随便给一个参数值就行了。
      

  3.   

    WebLogic Server supports an automatic primary key generation feature for container-managed persistence (CMP). Note: This feature is supported for the EJB 2.0 CMP container only, there is no automatic primary key generation support for EJB 1.1 CMP. For 1.1 beans, you must use bean-managed-persistence (BMP.)
      

  4.   

    有一个问题:
    如果我在ejbcreate中用到sequence.nextval,在ejbstroe不知传什么关键值,老是说记录不存在,这种情况能解决吗