简体   繁体   English

Spring3 /休眠声明失败

[英]Spring3/Hibernate AssertionFailure

Here is a simple hibernate code that inserts a value into a table. 这是一个简单的休眠代码,它将值插入表中。 If the row already exists, query the row and return the data. 如果该行已经存在,请查询该行并返回数据。 Most of the time, the code works fine with no issues. 在大多数情况下,代码可以正常工作而不会出现问题。

In a very special case, three different clients are trying to insert the exact the same row into the table. 在一个非常特殊的情况下,三个不同的客户端试图将完全相同的行插入表中。 Ofcourse, only one row gets inserted. 当然,仅插入一行。 The other two insertions fail and the fall into the try-catch block. 其他两次插入失败,并落入try-catch块中。

There is a query in the try catch block, which queries the data and sends the value to the client. 在try catch块中有一个查询,该查询查询数据并将值发送给客户端。 This results in an error for subsequent operations on the session. 这会导致会话的后续操作出错。

Hibernate throws "ERROR org.hibernate.AssertionFailure - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)" in the logs. Hibernate在日志中引发“错误org.hibernate.AssertionFailure-断言失败(这可能表示Hibernate中的错误,但很可能是由于会话的不安全使用所致)”。

Here is the code. 这是代码。 What would be the right way to handle this scenario? 处理这种情况的正确方法是什么?

@Override
public void addPackage(PackageEntity pkg) {

    try{

        getCurrentSession().save(pkg);
        getCurrentSession().flush();

    }catch( ConstraintViolationException cve ){

        // UNIQ constraint is violated
        // query now, instead of insert
        System.out.println("Querying again because of UNIQ constraint : "+ pkg);
        PackageEntity p1 = getPackage(pkg.getName(), pkg.getVersion());

        if( p1 == null ){
            // something seriously wrong
            throw new RuntimeException("Unable to query or insert " + pkg);
        }else{
            pkg.setId(p1.getId());
        }

    }catch (Exception e) {
        e.printStackTrace();
    }catch (Throwable t) {
        t.printStackTrace();
    }
}

Primary (or) composite Key makes each row data unique and avoids this error. 主(或)复合键使每一行数据唯一,并避免此错误。

If you need the data from all these three requests then create a unique primary key in your table and add it to the entity. 如果您需要所有这三个请求的数据,则在表中创建一个唯一的主键,并将其添加到实体中。

Primary Key could be any unique thing from your data, an auto generated sequence or UUID/GUID. 主键可以是数据中的任何唯一事物,自动生成的序列或UUID / GUID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM