在具有已知主键的情况下在 Hibernate 中保留对象。

发布于 2024-11-26 19:30:03 字数 606 浏览 0 评论 0原文

我的问题是分离的对象......

我目前正在使用 Spring 和 Hibernate。

我有一个映射对象,其主键为字符串(我知道这很糟糕......但重构代码需要几个月的时间),我希望保留它。 (我只用两个属性简化了对象)

@Id
private String id;

private String pattern;

因此,例如我想添加类似的内容:

["id":"myFirstPattern","pattern":".*"]

请注意,我的主键已经设置。问题是,每当我尝试持久化时,Hibernate 都会尝试将此对象与上下文中的任何对象(因为主键)链接起来,但会失败,因为没有。引发分离对象错误。

我做了一些研究并得出结论, merge() 可以满足我的需求,因为即使对象不可用,它也会持续存在并更新。然而,我发现这是一个相当肮脏的解决方法,并想检查是否还有其他解决方案来解决这个问题。

考虑到我们有一个 Helper 层,因此 Services 层不会直接与 HibernateDao 层一起工作。因此,我可以通过添加将调用相同合并 DAO 方法的“持久”和“更新”方法来“掩盖”这一点。

谢谢, 弗拉维奥.

My problem is with detached objects...

I am currently using Spring with Hibernate.

I have a mapped object that has a primary key as a String (I know it sucks... but refactoring the code would take months), and I wish to persist it. (I have simplified the object with just two attributes)

@Id
private String id;

private String pattern;

So for example I want to add something like:

["id":"myFirstPattern","pattern":".*"]

Notice that my primary key is already set. The problem with that is that whenever I try to persist, Hibernate will try to link this object with any object within the context (because of the primary key) and will fail to do so, since there are none. Throwing a detached object error.

I've done some research and came to the conclusion that merge() would suffice my needs, since it persists and updates even if the object is not available. However I found this a rather dirty workaround and wanted to check if there are any other solutions to this problem.

Take into account that we have a Helper layer, so Services layer will not work directly with the HibernateDao layer. So I can "mask" this by adding 'persist' and 'update' methods that will invoke the same merge DAO method.

Thanks,
Flavio.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

莳間冲淡了誓言ζ 2024-12-03 19:30:03

您尝试过保存或更新吗?

Session sess = factory.openSession();
Transaction tx;
try {
    tx = sess.beginTransaction();
    session.saveOrUpdate( yourObjectHere );

    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    sess.close();
}

Have you tried saveOrUpdate?

Session sess = factory.openSession();
Transaction tx;
try {
    tx = sess.beginTransaction();
    session.saveOrUpdate( yourObjectHere );

    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    sess.close();
}
与之呼应 2024-12-03 19:30:03

在尝试了毛里西奥给我的想法后,我尝试使用一些不同的方法。由于 SaveOrUpdate 使用缓存的实体来验证是否应该更新或保存对象,因此我考虑在保存对象之前进行澄清。

所以,这是我的一段代码:

try {
        getHibernateTemplate().clear();
        getHibernateTemplate().save(entity);
    } catch (DataAccessException e) {
        if (e.getCause() instanceof ConstraintViolationException)
            throw new HibernateDaoException("Entity could not be persisted. Constraint violation.");
        throw new HibernateDaoException(e);
    }

目前,它正在按预期工作,尽管它似乎会杀死我的缓存数据库存在的理由...但是,此更新功能将被谨慎使用,因为这是组件返回信息、匹配模式并返回最佳结果。

无论如何,如果我发现任何缺陷,我会尽快回来。

有任何意见,欢迎留言:)

I tried using some different approach after I tried the idea Mauricio gave to me. Since SaveOrUpdate was using the cached entities to verify if it should update or save an object I thought about making a clear just before saving my object.

so, here is my piece of code:

try {
        getHibernateTemplate().clear();
        getHibernateTemplate().save(entity);
    } catch (DataAccessException e) {
        if (e.getCause() instanceof ConstraintViolationException)
            throw new HibernateDaoException("Entity could not be persisted. Constraint violation.");
        throw new HibernateDaoException(e);
    }

For now, it is working as expected, even though it seems that it will kill my cached database reason to exist... However this update feature will be used sparingly, as the main reason for the component is returning info, matching patterns and returning the best results.

Anyway I will return soon if I find any flaws.

Any comments, please feel free to post them :)

撩起发的微风 2024-12-03 19:30:03

我不确定,我现在无法自己尝试,但没有设置 @Id 属性来使用 "assigned" 生成器正是这样做的吗?

I'm not certain, and I can't try it myself right now, but doesn't setting the @Id property to use the "assigned" generator do exactly that?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文