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?

Rob
  • 2,466
  • 3
  • 22
  • 40
  • First implement solution and then later check if for any case the bean contains out of date information. – Phani Apr 16 '12 at 10:38

1 Answers1

5

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

Perception
  • 79,279
  • 19
  • 185
  • 195
  • So what you're saying is that I shouldn't keep data in memory but load it from the DB each time a call is made? – Rob Apr 16 '12 at 10:59
  • Yes, in this case definitely. You typically only cache data that is static over ***long*** periods of time. – Perception Apr 16 '12 at 11:06
  • You should let the JPA framwework cache the data (with the second-level cache). Otherwise, you're re-inventing the wheel, plus it's likely to be buggy. – ewernli Apr 16 '12 at 11:12
  • Thanks, yes this would make everything work. I just had to let go of the idea that loading data on each call is to expensive. – Rob Apr 16 '12 at 11:17