Question

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?

Was it helpful?

Solution

I am not sure what your design problem is exactly, as a stateless bean should not be holding onto ... state. You should be retrieving the user group on demand, updating it, then persisting back to the DB. If you are really worried about concurrent updates and need tighter control then try using a lock mode on your entity:

  • JPA 1.0 supports optimistic locking via version numbers (OPTIMISTIC, OPTIMISTIC_FORCE_INCREMENT).
  • JPA 2.0 adds pessimistic locking (INCREMENT, PESSIMISTIC_FORCE_INCREMENT)

Only use pessimistic locking if you have a high amount of contention in your system for the same entities, as it does not scale well.

Additional Reading and Examples

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top