兩種方法。一﹐象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語句一起插入記錄進數據庫。
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語句一起插入記錄進數據庫。
<automatic-key-generation> <generator-type>SQL_SERVER</generator-type>
</automatic-key-generation>
当通过实体Bean在数据库中插入数据时,只要在EntityBean的create()中的自增主键随便给一个参数值就行了。
如果我在ejbcreate中用到sequence.nextval,在ejbstroe不知传什么关键值,老是说记录不存在,这种情况能解决吗