Search code examples
hibernatecdiweld

Injection in custom ConnectionProvider with CDI and Hibernate4


in Java EE 7 Project i need a custom ConnectionProvider, which call DB-Function with logged UserId, and set as DB-Session variables.

My Problem, I can't inject my logged User in MyConnectionProvider, but in all other Beans - without problem.

This is my ConnectionProvider:

@SessionScoped
@Named
public class MyConnectionProvider implements ConnectionProvider, Configurable, Serializable {

@Inject
private Logger log;

@Inject @LoggedIn
private User currentUser = null;

Here is class Login where is the currentUser initialized:

@SessionScoped
@Named
public class Login implements Serializable
{

@Inject
private Credentials credentials;

@PersistenceContext
private EntityManager userDatabase;

private User currentUser;

//.....................................

@Produces
@LoggedIn
@Named
@SessionScoped
public User getCurrentUser()
{
  return currentUser;
}

and interface LoggedIn:

@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, PARAMETER,  METHOD, FIELD})
@Qualifier
public @interface LoggedIn {}

May be anyone has the same Problems ?


Solution

  • Hibernate does not provide any injection support with these classes. They are instantiated directly, and always are a singleton within your persistence unit.

    You can still get this kind of functionality, just use the CDI utility class to look up your references. CDI.current().select(User.class, new LoggedInLiteral()).get() where User.class is the class of the type you're expecting, and LoggedInLiteral is a qualifier instance.