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.