我有类似的批处理要求,进程运行在多个JVM上。我为此采取的方法如下。这很像jtahlborn的建议。但是,正如vbence所指出的,如果您使用NESTED事务,则当您遇到约束违例异常时,您的会话将无效。相反,我使用REQUIRES_NEW,它会挂起当前事务并创建一个新的独立事务。如果新事务回滚,则不会影响原始事务。
我正在使用Spring的TransactionTemplate,但如果您不希望依赖Spring,可以肯定可以轻松地对其进行翻译。
public T findOrCreate(final T t) throws InvalidRecordException { // 1) look for the record T found = findUnique(t); if (found != null) return found; // 2) if not found, start a new, independent transaction TransactionTemplate tt = new TransactionTemplate((PlatformTransactionManager)transactionManager); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); try { found = (T)tt.execute(new TransactionCallback<T>() { try { // 3) store the record in this new transaction return store(t); } catch (ConstraintViolationException e) { // another thread or process created this already, possibly // between 1) and 2) status.setRollbackonly(); return null; } }); // 4) if we failed to create the record in the second transaction, found will // still be null; however, this would happy only if another process // created the record. let's see what they made for us! if (found == null) found = findUnique(t); } catch (...) { // handle exceptions } return found;}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)