Filippo
Filippo

Reputation: 1159

Is it possible to inject a context specific PersistenceContext?

In a jsf application data is managed injecting a PersistenceContext.

 @PersistenceContext(unitName = "MyPU")
 private EntityManager em;

PersistenceContext is static and choosen at compile time. Is there a way to inject a different PersistenceContext based on the user ? My idea is to enforce authorization checks on database side too, so if there is a hole in application security the user cannot access or modify restricted data.

Upvotes: 1

Views: 35

Answers (1)

grigouille
grigouille

Reputation: 705

Create some factory :

@Stateless
public class PersistenceContextFactory {
  @PersistenceContext(unitName="MyPU")
  private EntityManager emPU;

  @PersistenceContext(unitName="MyOtherPU")
  private EntityManager emOtherPU;

  public EntityManager getEntityManager(User user) {
    if(user.hasSomeRight()) {
      return emPU;
    } else {
      return emOtherPU;
    }
  }
}

Upvotes: 0

Related Questions