Within an EJB, there is a way to provide different data sources to different user sessions. This is one way to prevent unauthorized users from updating restricted data. Since the EJB security model provides for the discovery of the invoking client, you can easily determine a user's identity and assigned roles. Programmatically restricting data access to specific users can make your code less flexible and maintainable. In order to switch data sources for a particular user, first of all we have to determine which user is calling an EJB method. In our sample we expect to accounts access 'User1' and 'User2'. Deployment descriptor has corresponding declarations:

////////////// EJB code retreiving data source connection:

public class UserDBBean implements SessionBean {
  private SessionContext _session;
  public void setSessionContext(SessionContext session) {
    _session = session;
  public Connection getConnection() throws SQLException {
    try {
      Principal user = _session.getCallerPrincipal();
      String username = user.getName();
      String source = "java:comp/env/" + username + "ejbDB";
      InitialContext context = new InitialContext();
      System.out.println("Retreive connection:" + source);
      System.out.println("Principal name:" + username);

      return (DataSourcecontext.lookup(source)).getConnection();

    catch (NamingException error) {
      throw new EJBException(ne);

////////////// necessary configuration in deployment descriptor:

    <!-- main bean definitions -->
      <!-- definition of resources bean referes -->