Skip to content

Instantly share code, notes, and snippets.

@rcaneppele
Created January 15, 2015 11:49
Show Gist options
  • Save rcaneppele/fc5f16ffc0adafe8dd1d to your computer and use it in GitHub Desktop.
Save rcaneppele/fc5f16ffc0adafe8dd1d to your computer and use it in GitHub Desktop.
CDI Multiple EntityManager producers
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR})
public @interface Bd2 {
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR})
public @interface Bd3 {
}
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
@ApplicationScoped
public class EntityManagersProducer {
@PersistenceContext(unitName = "bd1")
private EntityManagerFactory factoryBd1;
@PersistenceContext(unitName = "bd2")
private EntityManagerFactory factoryBd2;
@PersistenceContext(unitName = "bd3")
private EntityManagerFactory factoryBd3;
@Produces
@RequestScoped
@Default
public EntityManager createEntityManagerBd1() {
return factoryBd1.createEntityManager();
}
@Produces
@RequestScoped
@Bd2
public EntityManager createEntityManagerBd2() {
return factoryBd2.createEntityManager();
}
@Produces
@RequestScoped
@Bd3
public EntityManager createEntityManagerBd3() {
return factoryBd3.createEntityManager();
}
}
import javax.inject.Inject;
import javax.persistence.EntityManager;
public class MinhaDao {
@Inject
private EntityManager emBd1;
@Inject
@Bd2
private EntityManager emBd2;
@Inject
@Bd3
private EntityManager emBd3;
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment