Updating hibernate version manually

。_饼干妹妹 提交于 2019-12-01 01:12:41

问题


I have two classes say Foo and Bar mapped as @OneToOne (bidirectional) using Hibernate (3.6.1 final) with JPA (2.0) like -

@Entity
public class Foo{
    @Id
    private Long id;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "foo")
    private Bar bar;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "foo")
    private Qux qux;

    @Version
    private int version;

    // getters and setters omitted
}

@Entity
public class Bar{
    @Id
    private Long id;

    @OneToOne
        @JoinColumn(name = "foo_id",  nullable = false)
    private Foo foo;

    // getters and setters omitted
}

@Entity
public class Qux {
    @Id
    private Long id;

    @OneToOne
        @JoinColumn(name = "foo_id",  nullable = false)
    private Foo foo;

    // getters and setters omitted
}

Note that - Bar and Qux doesn't have @Version column

If we update Bar then hibernate will not increment the version of Foo and same for Qux. But our business logic needs - if someone updates Bar in the Foo and other thread is trying to update the Qux of the same Foo but doesn't have updated Bar and vice versa then such updates should fail.
Since hibernate doesn't update the version property of Foo if we update the Bar, we decided to update the version of Foo manually (I know it's pretty weird and not recommended) if we update the Bar and Qux.
It works perfectly fine.. but I'm worry about some corner cases in concurrency which may fail this or will have unintended behavior.
Is it safe to do this kind of tweak with version for this purpose? OR is there any other better alternative to this (I've already tried optimistic/pessimistic force increament)


回答1:


The correct way to force version update is the following:

em.lock(entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

It's intended to be used in such cases.

Other methods of EntityManager that take LockModeType can be used as well.



来源:https://stackoverflow.com/questions/5299430/updating-hibernate-version-manually

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!