栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Hibernate根据唯一键查找或插入

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Hibernate根据唯一键查找或插入

我有类似的批处理要求,进程运行在多个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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/454161.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号