Interface and inheritance for the Java connection class

Asked

Viewed 614 times

6

Considering the object orientation, would the use of inheritance and interface in this way be correct? But in this way, any request for connection to the database will need a new object. Would have some way to statically access or would need a new object created when initializing the system using Singleton?

Connection interface

public interface ConnectionDB {
    public Connection getConnection();
}

Genericconnection class

public class GenericConnection {

    protected static Properties dbProperties = new Properties();    

    public static Properties getDbProperties() {
        if(dbProperties == null){
            try {
                dbProperties.load(new FileInputStream("src/properties/conf.properties"));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(GenericConnection.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(GenericConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return dbProperties;
    }

    public static void setDbProperties(Properties dbProperties) {
        GenericConnection.dbProperties = dbProperties;
    }
}

Oracleconnection class

public class OracleConnection extends GenericConnection implements ConnectionDB {

    private Connection conn;
    private Statement st;

    public Statement getSt() {
        return st;
    }

    public void setSt(Statement st) {
        this.st = st;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    @Override
    public Connection getConnection() {
        if (getConn() != null) {
            return getConn();
        } else {
            try {
                String url = "jdbc:oracle:thin:@" + getDbProperties().getProperty("ServerOracle") + ":" + getDbProperties().getProperty("portOracle") + ":" + getDbProperties().getProperty("sidOracle");
                setConn(DriverManager.getConnection(url, getDbProperties().getProperty("userOracle"), getDbProperties().getProperty("passwdOracle")));
                setSt(getConn().createStatement());
                return getConn();
            } catch (SQLException ex) {
                Logger.getLogger(OracleConnection.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }
    }

}

2 answers

5


It’s hard to say for certain, some say it’s as certain as possible, others say it’s a waste to have to create new objects all the time.

Particularly I would make a Singleton. But I don’t know the specific need. This class is almost a.

There is a serious error in this implementation since the mother class only has static members, so it will not inherit anything.

Maybe until it was the case of having everything static, but then it would not make sense to use inheritance.

What I think is that this interface is unnecessary. It seems to me that the class GenericConnection should be abstract and contain the method getConnection() without implementation to let the concrete class solve this. I actually think that a good part of what’s in the derivative class could be in the inherited class.

Example:

public abstract class GenericConnection {

    private Connection conn;
    private Statement st;

    public Statement getSt() {
        return st;
    }

    public void setSt(Statement st) {
        this.st = st;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    protected Properties dbProperties = new Properties();    

    public Properties getDbProperties() {
        if (dbProperties == null) {
            try {
                dbProperties.load(new FileInputStream("src/properties/conf.properties"));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(GenericConnection.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(GenericConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return dbProperties;
    }

    public void setDbProperties(Properties dbProperties) {
        GenericConnection.dbProperties = dbProperties;
    }

    public Connection getConnection();
}

public class OracleConnection extends GenericConnection {

    @Override
    public Connection getConnection() {
        if (getConn() != null) {
            return getConn();
        } else {
            try {
                String url = "jdbc:oracle:thin:@" + getDbProperties().getProperty("ServerOracle") + ":" + getDbProperties().getProperty("portOracle") + ":" + getDbProperties().getProperty("sidOracle");
                setConn(DriverManager.getConnection(url, getDbProperties().getProperty("userOracle"), getDbProperties().getProperty("passwdOracle")));
                setSt(getConn().createStatement());
                return getConn();
            } catch (SQLException ex) {
                Logger.getLogger(OracleConnection.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }
    }
}

I put in the Github for future reference.

Just an improved example, I’m not saying you should use exactly this.

  • 1

    In fact I took a class ready that I used and tried to apply the inheritance without knowing if it would work because I didn’t test it yet, I used everything static, but each class I repeated the attributes and the getConnection() method, I don’t like to keep creating objects all the time, How do you think I could do it. Put only abstract getConnection() and the rest in the specific child classes in the mother class, I will create one for Sqlserver and one for Oracle.. In fact I will create a little financial control software for myself as learning.

  • I think the way I put it might be a way. Actually I do it very differently from everyone else, but it works for me ,I don’t teach other people to do the same.

  • I don’t know if it works, but I tried to create several projects, for example. a project of access to the dao where the connection is and all the daos, and a package where the registration screens are. Referencing the project dao in the libraries. but does not find the property file, can tell me why?

  • Gives this error: Jul 27, 2016 9:30:41 AM Conection.Genericconnection getDbProperties GRAVE: null java.io.Filenotfoundexception: src properties conf.properties (The system cannot find the specified path)

  • There is some other more specific problem. needs another more specific question.

  • Make sure it’s right the way I did.. a Oracleconnection https://drive.google.com/file/d/0B91j9PUXTgJscVBUMS1sMlBrZzg/view?usp=sharing / the mother class https://drive.google.com/filed/0B91j9PUXTgJsWDhzd19ma0ptbA/view?usp=sharing

  • I’m going to create another more specific question.. I wanted to make sure the rest is correct

  • It looks much better, I still don’t know if it’s ideal, but as I said, I like to do different.

Show 3 more comments

1

The comment was going to get too big so it turned out to be an answer.

I’m not sure I understand the issue of creating objects all the time, but unless you’re doing batch operations it’s best that every bank operation is done by one Connection different. This is because reusing the same connection for two requested operations in a spaced interval can cause timeouts undesirable.

On the subject of object orientation, I would avoid creating a generic DAO from which other Daos inherit. There is one caelum’s post explaining that it is an unnecessary use of inheritance.

As for how to get the properties strings to create the connections, I would prefer to read them from the file in a separate code and then pass them to a class FabricaDeConexoes via constructor (this class would have a method criarConexao()), and then pass that object fabrica for each DAO also via DAO builder.

Note that I didn’t get into the question of having a pool of connections, which in your case may not even be necessary.

I accept criticism and suggestions.

  • Then it would be interesting to each connection with the bank I create a new connection, instead of reusing the same one I logged into the system. And I use a controller and an abstract dao, this is not interesting?

  • I don’t know what to say about the controller, here I’m just talking about access to data. Your abstract DAO has a responsibility that is not his. He has no obligation to access the property file and read it. Nor should it be, I think, the responsibility of the connection factory.

  • Actually these question classes are of connections, not the access to DAO. Did I understand your suggestion?

  • True. I don’t know where I got the DAO from. But if you were wearing one, it would be quite appropriate. It’s one of the basic things worth learning. My contribution then is the following: Your Oracleconnection should be a Manufacturing Connection. The responsibility of reading the file is not hers. And for each bank operation a connection (except when doing batch operations).

  • Additionally, study on Preparedstatement (mainly to prevent SQL Injection attacks) and do not capture Sqlexception, let it be treated by the level above.

  • When said level up, I mean with Throwsexception returning responsibility for the frame, or it could be?

  • Yes, for the frame, if there is no middle layer. Preferably encapsulated in an Accessoadadosexception, so that it is not evident that it is SQL (the way the data is saved does not matter to the top layer).

  • thanks, thank you very much...

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.