Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Fundacao;
- import Apresentacao.DataAccessDTO;
- import Dominio.Entity;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public abstract class Repository<T extends Entity> {
- private static Connection conn;
- private final String DRIVER = "oracle.jdbc.OracleDriver";
- protected String sql;
- private boolean connected = false;
- private String engine = "jdbc:oracle:";
- private boolean connect() throws SQLException {
- return this.connect(DataAccessDTO.host, DataAccessDTO.user, DataAccessDTO.password);
- }
- private boolean connect(String host, String user, String password) throws SQLException {
- try {
- Class.forName(DRIVER);
- String driverLink = engine + "oci:@" + host + ":1521";
- System.out.print(driverLink);
- conn = DriverManager.getConnection(driverLink, user, password);
- conn.setAutoCommit(false);
- this.connected = true;
- }catch (ClassNotFoundException e){
- System.out.println("Driver JDBC Não encontrado " + e.getMessage());
- } catch (SQLException e) {
- System.out.println("ERRO QUERY " + e.getMessage());
- }
- return this.connected;
- }
- private void disconnect() {
- try {
- Class.forName(DRIVER);
- conn = null;
- this.connected = false;
- } catch (ClassNotFoundException ex) {
- System.out.println("Driver JDBC Não encontrado " + ex.getMessage());
- }
- }
- protected ResultSet executeQuery(String sql) throws SQLException {
- if (this.connect()) {
- Statement statement = conn.createStatement();
- ResultSet result = statement.executeQuery(sql);
- this.disconnect();
- return result;
- }
- return null;
- }
- public void insert(T obj) throws SQLException {
- this.persistInsert(obj);
- ResultSet res = this.executeQuery(this.sql);
- obj.setId(res.getInt("id"));
- }
- public void update(T obj) throws SQLException, Exception {
- if (obj.getId() == 0) {
- throw new Exception("Não é possivel atualizar o registro sem um 'ID' na Entidade.");
- }
- this.persistUpdate(obj);
- this.executeQuery(this.sql);
- }
- public void delete(T obj) throws SQLException {
- this.persistDelete(obj);
- this.executeQuery(this.sql);
- }
- protected void persistInsert(T obj) {
- }
- protected void persistDelete(T obj) {
- }
- protected void persistUpdate(T obj) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement