Java – Cross class access H2 connection

I'm trying to avoid static and singleton and integrate the local H2 database into my JavaFX application (java8) The other five classes (including the controller) need to access the database, so I tried to share an H2 connection between them I've read the connection pool to avoid unnecessary reconnection, but I'll be confused if it applies to this Desktop use, single user

The following extrasdb class contains three methods, initializedb, getdbvalues and performquery In the past, these methods were static. I would use extrasdb Getdbvalues () calls them from other classes and uses the results accordingly, but since my application uses multiple threads, I'm looking for a better method I am removing all static / singleton usage from my application

The initializedb method creates connections and tables if necessary, and this method is called only once from the initialize method of my master controller This will cause the connection conn to be isolated from the instance and inaccessible to other class calls to getdbvalues or performquery, resulting in a null result set How to make the database connection accessible to all necessary classes so that these classes can freely access the database using the above methods?

public class ExtrasDB {

    final String JDBC_DRIVER = "org.h2.Driver";
    final String DB_URL = "jdbc:h2:~/mainDB";
    final String USER = "test";
    final String PASS = "test";
    Connection conn = null;
    Statement statement = null;
    String myStatement;
    ResultSet rs;
    DatabaseMetaData Meta;

    public void initializeDB() {

        try {
            Class.forName("org.h2.Driver");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
            System.out.println("Connected to database successfully...");
            statement = conn.createStatement();
            Meta = conn.getMetaData();
            rs = Meta.getTables(null,null,"EXTRAS",new String[]{"TABLE"});  // <--- Checks for existence of table "EXTRAS"

            if (!rs.next()) {

                System.out.println("Table doesn't exist yet... Creating...");
                sql = "CREATE TABLE EXTRAS " +
                        "(column_1 VARCHAR(255)," +
                        " column_2 VARCHAR(255))";

                statement.executeUpdate(sql);
            }
        } catch (sqlException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    public void getDBValues() throws sqlException {
        rs = statement.executeQuery("SELECT * FROM EXTRAS");
        while (rs.next()) {
            //..... do something
        }
    }

    public void performQuery(String query) {
        try {
            statement.executeUpdate(query);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Solution

If you do not want some kind of static access, there are two options:

>Create a service factory instance (non static) when the program starts Service factory is a POJO class that contains all dependencies to be shared in other classes These dependencies can be created by service factory or set by setter All classes requiring some dependencies only need to provide factory instances. > You can use some frameworks to implement automatic dependency injection With such a framework, you only need to annotate constructors or fields For more information about dependency injection, see this link; See this tutorial for how to use the spring framework for dependency injection

Use the first option in my JavaFX - app I have a class named root and it's in JavaFX application. Application:: create its instance in the start function Some dependencies are created by the root class, and others (such as controller instances) are set using setters Because I load my controller through the fxml loader, I cannot use the constructor to provide a root instance, but each controller has an init function

public void initialize(Root root);

If you need more help Feel free to comment on the answer

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>