Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Interfaces;
- 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 Repositorio<T extends Entity> {
- private static Connection conn;
- private final String DRIVER = "com.mysql.jdbc.Driver";
- private String host;
- protected String sql;
- private String MySQL = "jdbc:mysql://";
- private boolean connected = false;
- public Repositorio() {
- }
- public boolean connect() throws SQLException {
- return this.connect(DataAccessDTO.host, DataAccessDTO.user, DataAccessDTO.password, DataAccessDTO.database);
- }
- private boolean connect(String host, String user, String password, String dbName) throws SQLException {
- this.host = host;
- try {
- Class.forName(DRIVER);
- String dbMySQL = MySQL + host + "/" + dbName;
- conn = DriverManager.getConnection(dbMySQL, user, password);
- conn.setAutoCommit(false);
- this.connected = true;
- } catch (ClassNotFoundException ex) {
- System.out.println("Driver JDBC Não encontrado");
- }
- return this.connected;
- }
- public void Disconnect() {
- try {
- Class.forName(DRIVER);
- conn = null;
- this.connected = false;
- } catch (ClassNotFoundException ex) {
- System.out.println("Driver JDBC Não encontrado");
- }
- }
- public ResultSet executeQuery(String sql) throws SQLException {
- this.connect();
- Statement statement = this.conn.createStatement();
- ResultSet result = statement.executeQuery(sql);
- this.Disconnect();
- return result;
- }
- 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 abstract Object persistInsert(Object obj);
- protected abstract Object persistDelete(Object obj);
- protected abstract Object persistUpdate(Object obj);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement