Solucionado (ver solução)
Solucionado
(ver solução)
5
respostas

Conectar dois bancos utilizando JPA e CDI

Olá,

Estou tentando fazer conexão em dois bancos e não estou conseguindo fazer funcionar.

Um banco é o SQL Server e o outro é o PostgreSQL.

Código do persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="CoNuBackPU" transaction-type="JTA">
        <jta-data-source>java:app/JNDICONUBACK</jta-data-source>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="eclipselink.logging.level" value="FINE"/>
        </properties>
    </persistence-unit>
    <persistence-unit name="HABITACAOPU" transaction-type="JTA">
        <jta-data-source>java:app/JNDIHABITACAO</jta-data-source>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="eclipselink.logging.level" value="FINE"/>
        </properties>
    </persistence-unit>
</persistence>

Código do bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">

</beans>

Código do glassfish-resources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="net.sourceforge.jtds.jdbcx.JtdsDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="jtds_sql_cadastros_pmrcPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="192.168.1.242"/>
        <property name="portNumber" value="1433"/>
        <property name="databaseName" value="cadastros"/>
        <property name="User" value="user"/>
        <property name="Password" value="123"/>
        <property name="URL" value="jdbc:jtds:sqlserver://192.168.1.242:1433/cadastros"/>
        <property name="driverClass" value="net.sourceforge.jtds.jdbc.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="java:app/JNDICONUBACK" object-type="user" pool-name="jtds_sql_cadastros_pmrcPool"/>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_habitacao_postgresPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="5432"/>
        <property name="databaseName" value="habitacao"/>
        <property name="User" value="postgres"/>
        <property name="Password" value=""/>
        <property name="URL" value="jdbc:postgresql://localhost:5432/habitacao"/>
        <property name="driverClass" value="org.postgresql.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="java:app/JNDIHABITACAO" object-type="user" pool-name="post-gre-sql_habitacao_postgresPool"/>
</resources>

Agora como é feito com a conexão. Com um banco dá certo. Agora estou tentando adicionar dois e não sei se precisa duplicar os arquivos, como por exemplo o TransactionInterceptor.

EntityManagerProducer.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.jpa;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Alternative;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

@ApplicationScoped
public class EntityManagerProducer {

    private final EntityManagerFactory factory;

    private final EntityManagerFactory factoryHabitacao;

    public EntityManagerProducer() {
        this.factory = Persistence.createEntityManagerFactory("CoNuBackPU");
        this.factoryHabitacao = Persistence.createEntityManagerFactory("HABITACAOPU");
    }

    @Produces
    @RequestScoped
    @Default
    public EntityManager create() {
        return factory.createEntityManager();
    }

    @Produces
    @RequestScoped
    @Alternative
    @TransactionalHabitacao
    public EntityManager createHabitacao() {
        return factoryHabitacao.createEntityManager();
    }

    public void close(@Disposes EntityManager manager) {
        manager.close();
    }

}

TransactionInterceptor.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.jpa;

import java.io.Serializable;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

@Interceptor
@Transactional
public class TransactionInterceptor implements Serializable {

    private static final long serialVersionUID = 1L;

    private @Inject EntityManager manager;

    @AroundInvoke
    public Object invoke(InvocationContext context) throws Exception {
        EntityTransaction transaction = manager.getTransaction();
        boolean owner = false;

        try {
            if (!transaction.isActive()) {
                // truque para fazer rollback no que já passou
                // (senão, um futuro commit, confirmaria até mesmo operações sem transação)
                transaction.begin();
                transaction.rollback();

                // agora sim inicia a transação
                transaction.begin();

                owner = true;
            }

            return context.proceed();
        } catch (Exception e) {
            if (transaction != null && owner) {
                transaction.rollback();
            }

            throw e;
        } finally {
            if (transaction != null && transaction.isActive() && owner) {
                transaction.commit();
            }
        }
    }

}

TransactionInterceptorHabitacao.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.jpa;

import java.io.Serializable;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

@Interceptor
@TransactionalHabitacao
public class TransactionInterceptorHabitacao implements Serializable {

    private static final long serialVersionUID = 1L;

    private @Inject EntityManager manager;

    @AroundInvoke
    public Object invoke(InvocationContext context) throws Exception {
        EntityTransaction transaction = manager.getTransaction();
        boolean owner = false;

        try {
            if (!transaction.isActive()) {
                // truque para fazer rollback no que já passou
                // (senão, um futuro commit, confirmaria até mesmo operações sem transação)
                transaction.begin();
                transaction.rollback();

                // agora sim inicia a transação
                transaction.begin();

                owner = true;
            }

            return context.proceed();
        } catch (Exception e) {
            if (transaction != null && owner) {
                transaction.rollback();
            }

            throw e;
        } finally {
            if (transaction != null && transaction.isActive() && owner) {
                transaction.commit();
            }
        }
    }

}

Transactional.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.jpa;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.interceptor.InterceptorBinding;

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Transactional {

}

TransactionalHabitacao.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.jpa;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.interceptor.InterceptorBinding;

/**
 *
 * @author michel
 */
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface TransactionalHabitacao {

}

Estou tentando ler um arquivo e gravar no banco PostgreSQL

LerArquivo.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ibge;

import br.com.habitacao.conuback.modelo.IBGE;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author michel
 */
public class LerArquivo {

    public static void main(String args[]) throws MalformedURLException, IOException {
        Scanner scanner = new Scanner(new URL("http://192.168.1.242:442/iptu/admin/importa/codigoCidadeUF.csv")
                .openStream(), "UTF-8").useDelimiter("\\n");
        while (scanner.hasNext()) {
            String dados = scanner.next();
            String dic[] = dados.split(",");

            String codigo = dic[0];
            System.out.println(codigo);

            String cidade = dic[1];
            System.out.println(cidade);

            String uf = dic[2];
            System.out.println(uf);

            EntityManagerFactory emf = Persistence.createEntityManagerFactory("HABITACAOPU");
            EntityManager em = emf.createEntityManager();
            try {
                IBGE ibge = new IBGE();
                ibge.setCodigo(Long.parseLong(codigo));
                ibge.setCidade(cidade);
                ibge.setUf(uf);

                em.getTransaction().begin();
                em.merge(ibge);
                em.getTransaction().commit();

            } catch (NumberFormatException e) {
                System.out.println("Erro na inserção de dados na tabela IBGE. " + e.getMessage());
            }

            System.out.println("----------------------------------------------");

        }
    }

}

Erro apresentando.

cd /home/michel/NetBeansProjects/CoNuBack; JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64 /usr/local/netbeans-8.2/java/maven/bin/mvn "-Dexec.args=-classpath %classpath ibge.LerArquivo" -Dexec.executable=java -Dexec.classpathScope=test org.codehaus.mojo:exec-maven-plugin:1.2.1:exec -Dcurrent.jrebel.agent.path=/home/michel/.netbeans/8.2/griffin/jrebel.jar
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...

------------------------------------------------------------------------
Building CoNuBack 1.0
------------------------------------------------------------------------

--- exec-maven-plugin:1.2.1:exec (default-cli) @ CoNuBack ---
1100015
Alta Floresta D'Oeste
Rondônia
[EL Info]: 2016-12-23 10:16:31.473--ServerSession(66233253)--Thread(Thread[main,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Severe]: ejb: 2016-12-23 10:16:31.483--ServerSession(66233253)--Thread(Thread[main,5,main])--Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:app/JNDIHABITACAO].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:app/JNDIHABITACAO].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:766)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:304)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:336)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:302)
    at ibge.LerArquivo.main(LerArquivo.java:40)
Caused by: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:app/JNDIHABITACAO].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at org.eclipse.persistence.exceptions.ValidationException.cannotAcquireDataSource(ValidationException.java:520)
    at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:109)
    at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162)
    at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.setOrDetectDatasource(DatabaseSessionImpl.java:204)
    at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:741)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:239)
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:685)
    ... 5 more
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:410)
    at javax.naming.InitialContext.lookup(InitialContext.java:421)
    at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:103)
    ... 10 more
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 0.993s
Finished at: Fri Dec 23 10:16:31 BRST 2016
Final Memory: 6M/150M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project CoNuBack: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Check Maven network proxy...

Um projeto que utilize apenas um banco de dados esta configuração funciona.

Agora quando tenho que trabalhar com dois bancos aí não estou conseguindo achar uma configuração que funcione.

Se alguém souber poste aí.

Valeu.

5 respostas

Olá Michel !

Eu configuraria o persistence.xml como resourceLocal somente para testar se os bancos e as classes funcionam corretamente. Depois eu partiria para o GlassFish.

Se não me engano quando se tem dois bancos tem que especificar para qual persistenceUnit ele pertence então acho que você que colocar as classe no persistence.xml para cada banco, segue o exemplo:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="CoNuBackPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>suas classes referente a esse banco</class>
        <properties>
            <property name="javax.persistence.jdbc.url"    value="jdbc:jtds:sqlserver://192.168.1.242:1433/cadastros" />
            <property name="javax.persistence.jdbc.driver" value="net.sourceforge.jtds.jdbc.Driver" />
            <property name="javax.persistence.jdbc.user" value="user" />
            <property name="javax.persistence.jdbc.password" value="123" />
            <property name="eclipselink.logging.level" value="INFO" />
            <property name="eclipselink.logging.level.sql" value="FINE" />
        </properties>
    </persistence-unit>

    <persistence-unit name="HABITACAOPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>suas classes referente a esse banco</class>
        <properties>
            <property name="javax.persistence.jdbc.url"    value="jdbc:postgresql://localhost:5432/habitacao" />        
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
            <property name="javax.persistence.jdbc.user" value="postgres" />
            <property name="javax.persistence.jdbc.password" value="" />
            <property name="eclipselink.logging.level" value="INFO" />
            <property name="eclipselink.logging.level.sql" value="FINE" />
        </properties>
    </persistence-unit>
</persistence>

Michel os bancos serão conectados simultaneamente ou hora um e hora outro ?

joao jose maranhao junior desta maneira realmente funciona.

Matheus Castiglioni, não precisa ser simultaneamente.

Agora o problema é o seguinte:

No exemplo anterior eu conseguia escolher o meu EntityManager, que está no arquivo lerArquivo.java

            EntityManagerFactory emf = Persistence.createEntityManagerFactory("HABITACAOPU");
            EntityManager em = emf.createEntityManager();

Agora para testar realmente o problema que eu quero resolver fiz a seguinte situação:

O persistence.xml ficou assim:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="CoNuBackPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>br.com.habitacao.conuback.modelo.Usuario</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:jtds:sqlserver://192.168.1.242:1433/cadastros" />
            <property name="javax.persistence.jdbc.driver" value="net.sourceforge.jtds.jdbc.Driver" />
            <property name="javax.persistence.jdbc.user" value="user" />
            <property name="javax.persistence.jdbc.password" value="123" />
            <property name="eclipselink.logging.level" value="INFO" />
            <property name="eclipselink.logging.level.sql" value="FINE" />
        </properties>
    </persistence-unit>

    <persistence-unit name="HABITACAOPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>br.com.habitacao.conuback.modelo.IBGE</class>
        <class>br.com.habitacao.conuback.modelo.UsuarioHabitacao</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/Teste" />        
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
            <property name="javax.persistence.jdbc.user" value="postgres" />
            <property name="javax.persistence.jdbc.password" value="" />
            <property name="eclipselink.logging.level" value="INFO" />
            <property name="eclipselink.logging.level.sql" value="FINE" />
        </properties>
    </persistence-unit>
</persistence>

No banco de dados cadastros tem uma tabela que se chama conu_usuario, nesta tabela tem as informações de login do sistema.

O modelo dela ficou assim: Usuario.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.modelo;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author michel
 */
@Entity
@Table(name = "conu_usuario")
public class Usuario implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    private String nome;
    private String login;
    private String senha;
    private Character status;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public Character getStatus() {
        return status;
    }

    public void setStatus(Character status) {
        this.status = status;
    }
}

E o DAO dela assim: UsuarioDAO.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.dao;

import br.com.habitacao.conuback.modelo.Usuario;
import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
import javax.persistence.EntityManager;

/**
 *
 * @author michel
 */
public class UsuarioDAO {

    @Inject
    private EntityManager em;

    @Inject
    private EntityManager emH;

    public Usuario entrarNoSistema(String login, String senha) {
        return em.createQuery("Select u "
                + "from Usuario u "
                + "where u.login = :login and u.senha = :senha", Usuario.class)
                .setParameter("login", login)
                .setParameter("senha", senha)
                .getSingleResult();
    }

    public Usuario entrarNoSistemaPostgre(String login, String senha) {
        return emH.createQuery("Select u "
                + "from UsuarioHabitacao u "
                + "where u.login = :login and u.senha = :senha", Usuario.class)
                .setParameter("login", login)
                .setParameter("senha", senha)
                .getSingleResult();
    }
}

No banco de dados PostegreSQL eu criei novamente a tabela usuario para tentar conectar com ela e criar a situação que eu quero.

A minha dúvida está neste DAO aí, veja que eu não sei como deve ficar a configuração da injeção para o sistema saber diferenciar qual @Inject eu quero utilizar.

No exemplo anterior eu passei como é feito esta criação do EntityManager, que são utilizados os arquivos EntityManagerProducer.java, TransactionInterceptor.java e o Transactional.java.

Com uma conexão funciona tranquilamente, no exemplo anterior tem outros arquivos como o TransactionInterceptorHabitacao.java e o TransactionalHabitacao.java. Estes arquivos são uma tentativa de tentar fazer o sistema conseguir diferenciar a injenção, mas como eu disse anteriormente não sei se é realmente necessário criar estes arquivos.

Tentei fazer desta maneira para ver se funcionava.

    @Inject
    private EntityManager em;

    @Inject
    @TransactionalHabitacao
    private EntityManager emH;

Mas dá a seguinte mensagem para a anotação @TransactionalHabitacao: annotation type not applicable to this kind of declaration

A configuração correta provavelmente está na utilização correta destes três arquivos EntityManagerProducer.java, TransactionInterceptor.java e o Transactional.java.

Como criei novamente a tabela usuario no PostgreSQL criei também o modelo para esta tabela.

UsuarioHabitacao.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.modelo;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author michel
 */
@Entity
@Table(name = "usuario")
public class UsuarioHabitacao implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    private String nome;
    private String login;
    private String senha;
    private Character status;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public Character getStatus() {
        return status;
    }

    public void setStatus(Character status) {
        this.status = status;
    }
}

Olá Michel !

No Blog da Alura tem um passo a passo com dois entityManager: http://blog.caelum.com.br/acessando-multiplos-bancos-de-dados-com-jpa-e-cdi/

Anota o seu EntityManagerFactory com o @PersistenceUnit(unitName = "HABITACAOPU")

Espero ter ajudado.

solução!

Olá joao jose maranhao junior ,

Eu já tinha visto este tutorial e não tinha conseguido fazer funcionar.

Agora tentei várias vezes aqui até achar o esquema correto e deu certo.

Aqueles arquivos que eu não sabia se teria que repetir para fazer uma nova conexão realmente não precisa.

EntityManagerProducer.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.jpa;

import java.io.Serializable;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Alternative;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

@ApplicationScoped
public class EntityManagerProducer implements Serializable {

    private final EntityManagerFactory factory;

    private final EntityManagerFactory factoryHabitacao;

    public EntityManagerProducer() {
        this.factory = Persistence.createEntityManagerFactory("CoNuBackPU");
        this.factoryHabitacao = Persistence.createEntityManagerFactory("HABITACAOPU");
    }

    @Produces
    @RequestScoped
    @Default
    public EntityManager create() {
        return factory.createEntityManager();
    }

    @RequestScoped
    @Produces
    @Habitacao
    public EntityManager createCorporativoEntityManager() {
        return factoryHabitacao.createEntityManager();
    }

    public void close(@Disposes EntityManager manager) {
        manager.close();
    }

}

Habitacao.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.habitacao.conuback.jpa;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

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

}

Obrigado pela ajuda e até mais.