OLá,
uma duvida queria ver se funiciona dessa forma o uso do acesso via JPA
do banco de dados utilizando uma conexão (Singleton) com acesso
via EntityManager.
E nos metodos (insert,update,delete,select) utilizo :
- inicio transação
- commit transação
Gostaria de uma opinião se dessa forma funciona ???
fico no aguardo de uma resposta …
abs
public class ServiceLocator {
private static String POOLING_NAME = "java:comp/env/jdbc/local";
//private static String POOLING_NAME = "jdbc/local";
private final static String DRIVER_NAME = "com.mysql.jdbc.Driver";
private final static String DB_URL = "jdbc:mysql://localhost:3306/xxxxx";
private final static String DB_USER_NAME = "root";
private final static String DB_PASSWORD = "root";
private boolean usePool = true;
protected DataSource ds;
private static EntityManagerFactory factory = null;
private static EntityManager manager = null;
static { //Busca o datasource configurado no arquivo resources.application existente em WEB-INF\classes\resources
ResourceBundle prop = ResourceBundle.getBundle("resources.application");
try {
POOLING_NAME = prop.getString("geral.datasource");
} catch (Exception e) {
}
}
private static InitialContext initCtx = null;
private static ServiceLocator instance = new ServiceLocator();
public static ServiceLocator getInstance() {
return instance;
}
public Connection getConnection() throws Exception {
if (usePool) {
System.out.println("pool");
return getConnectionByPool();
} else {
System.out.println("manual");
return getConnectionManual();
}
}
public Connection getConnectionManual() throws Exception {
Connection conn = null;
try {
factory = Persistence.createEntityManagerFactory("JPA9");
manager = factory.createEntityManager();
System.out.println("Conexão Aberta !!!");
} catch (Exception e) {
System.out.println("Conexão Não Aberta !!!");
e.printStackTrace();
throw new Exception("Erro ao obter conexao via JDBC: " ,e);
}
return conn;
}
public Connection getConnectionByPool() throws Exception {
Connection conn = null;
DataSource ds = null;
try {
if (initCtx == null) {
initCtx = new InitialContext();
}
System.out.println("PooLING="+POOLING_NAME);
ds = (DataSource) initCtx.lookup(POOLING_NAME);
conn = ds.getConnection();
System.out.println("Conexao Aberta");
} catch (Exception e) {
e.printStackTrace();
//throw new Exception("Erro ao obter conexao via JNDI: "
// + POOLING_NAME, e);
}
return conn;
}
public void setUsePool(boolean usePool) {
this.usePool = usePool;
}