0

I'm new to using ORM tools in enteprise applications. We're building a scaleable application that uses JPA 2.0 and EE6. I'm trying to find a nice pattern to build my application but I can't find a way to keep my entities in sync (I want to pool my beans that access the entities).

An example:

I have a Group:

@Entity
public class Group implements Serializable
{
    @Id
    private Long id;
    @OneToMany
    private List<MyUser> myUsers;

    public Group()
    {
    }

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public void addUser(MyUser u)
    {
        myUsers.add(u);
    }
}

And I have a user

@Entity
public class MyUser implements Serializable
{
    @Id
    private Long id;

    public MyUser()
    {
    }

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

}

Now if I would have a stateless bean that adds or removes users to a group, I risk having another instance of the stateless bean having out of date information. What is the best practice for this?

4

1 回答 1

5

我不确定您的设计问题到底是什么,因为无状态 bean 不应该保持...状态。您应该按需检索用户组,更新它,然后持久化回数据库。如果您真的担心并发更新并需要更严格的控制,请尝试在您的实体上使用锁定模式:

  • OPTIMISTICJPA 1.0 通过版本号 ( , OPTIMISTIC_FORCE_INCREMENT)支持乐观锁定。
  • JPA 2.0 增加了悲观锁 ( INCREMENT, PESSIMISTIC_FORCE_INCREMENT)

仅当系统中对相同实体有大量争用时才使用悲观锁定,因为它不能很好地扩展。

附加阅读和示例

于 2012-04-16T10:53:10.113 回答