我正在为我的应用程序使用hibernate。有时hibernate生成重复的ID,我使用的策略是增量,它从表中执行max(ID)并添加一个。我不知道它为什么会发生并且它突然发生,之后对该表插入操作的所有后续请求都失败了。解决方法是重新启动tomact服务器。
这里是应用程序的详细信息
1。在liferay-tomcat.each上部署的3个应用程序有自己的abstraction-impls.jar。这个JAR包含用于使用Hibernate与oracle交互的类。我怀疑这是导致这个问题的一个可能案例。
2。所有3个应用程序都有与hibernate相关的JAR
我做了以下测试以确认问题是否因为多线程而导致, 1)创建了3个线程,其中每个线程运行for循环20次以插入到同一个表中>我没有发现任何问题。一切顺利。
以下是上面的示例代码。
public class ThreadTest implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
UserManagement userManagement = new UserManagementImpl(-1);
Context context = new Context();
context.setUserId("testUser");
context.getUserContextMap().put("password", "shiva123");
try{
int sessionId = userManagement.login(context);
System.out.println("thread<<"+Thread.currentThread().getName() + ">> "+sessionId);
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadTest());
Thread t2 = new Thread(new ThreadTest());
Thread t3 = new Thread(new ThreadTest());
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}
如何获取正确的ID是问题或如何避免生成重复的ID?
以下是给我提问的代码。
以下是hibernate映射类。
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@javax.persistence.Entity
@Table(name="entities",
uniqueConstraints = {@UniqueConstraint(columnNames={"id"})})
@org.hibernate.annotations.GenericGenerator(
name = "test-increment-strategy",
strategy = "increment")
public class EntityImpl extends Entity {
/**
* Serial Version UID for this class
*/
private static final long serialVersionUID = -9214466697134157251L;
@Override
public String toString() {
return "EntityImpl [entityId=" + entityId + ", entityName="
+ entityName + ", entityType=" + entityType
+ ", parentEntityId=" + parentEntityId + ", entityHierarchy="
+ entityHierarchy + "]";
}
private int entityId;
private String entityName;
private String entityType;
private int parentEntityId;
private String entityHierarchy;
@Id
@GeneratedValue(generator = "test-increment-strategy")
@Column(name = "ID", nullable = false, updatable = false)
public int getEntityId() {
return entityId;
}
/** Sets the Entity ID for this instance */
public void setEntityId(int entityId) {
this.entityId = entityId;
}
/** Retrieves the name of this Entity instance */
@Column(name = "entity_name", nullable = false)
public String getEntityName() {
return entityName;
}
/** Sets the name of this Entity instance */
public void setEntityName(String entityName) {
this.entityName = entityName;
}
/** Retrieves the type of this Entity instance */
@Column(name = "entity_type", nullable = false, updatable = false)
public String getEntityType() {
return entityType;
}
/** Sets the type of this Entity instance */
public void setEntityType(String entityType) {
this.entityType = entityType;
}
/** Retrieves the Parent Entity ID for this instance */
@Column(name = "parent_id")
public int getParentEntityId() {
return parentEntityId;
}
/** Sets the Parent Entity ID for this instance */
public void setParentEntityId(int parentEntityId) {
this.parentEntityId = parentEntityId;
}
@Column(name = "ENTITY_HIERARCHY", nullable = false, updatable = false)
public String getEntityHierarchy() {
return entityHierarchy;
}
public void setEntityHierarchy(String entityHierarchy) {
this.entityHierarchy = entityHierarchy;
}
}
以下是保存实体的方法
private boolean save (Serializable object, Session session) throws EntityNotFoundException, InternalSystemException {
logger.debug("save() - start");
Transaction tx = null;
boolean successful = false;
boolean localInit = false;
try {
if (session == null) {
session = createSession();
tx = session.beginTransaction();
//session.save(object);
localInit = true;
}
session.save(object);
logger.debug("**********************************");
logger.debug("object: "+object);
logger.debug("**********************************");
if (localInit == true) {
tx.commit();
}
successful = true;
} catch(HibernateException ex) {
logger.error("error in saving entity "+ ex);
if (localInit == true && tx !=null)
tx.rollback();
ex.printStackTrace();
throw new InternalSystemException("error in saving entity "+ ex);
} catch(Exception ex) {
logger.error("error in saving entity "+ex);
if (localInit == true && tx !=null)
tx.rollback();
new InternalSystemException("error in saving entity "+ ex);
}finally {
if (localInit && session != null) {
session.flush();
session.clear();
session.close();
}
}
if (logger.isDebugEnabled()) {
logger.debug("save() - end");
}
return successful;
}
错误不会一直发生,但一旦发生,同样会继续,测试的oracle环境是Oracle RACK。
答案 0 :(得分:1)
在这种情况下不应使用增量策略。它包括将最大值加载到内存中的计数器中,然后在每次要求新ID时递增它。由于您部署了3个应用程序,因此您有3个这样的计数器,每个计数器都初始化为相同的初始值,因此它们将返回相同的ID。
这显然是documented:
增量
生成long,short或int类型的标识符,仅当没有其他进程将数据插入同一个表时才是唯一的。 做 不在群集中使用。
(强调不是我的)
序列生成器不会出现同样的问题。如果是这样,那么您要么在配置中遗漏了某些内容,要么三个应用程序中的一个继续使用增量策略,或者您从外部插入ID,或者数据库中序列的初始值是错误的。没有看到代码,ID的最大值以及序列的定义,很难说。