mardi 21 décembre 2021

implement Singleton inside model class is unrecognized [closed]

I have created an database connection with singleton design pattern.

I have also created an model called User, And I want to create an inner method which called save() which should getInstance() of the singleton and insert the model data to the Database.

But when I try to get the Instance of the singleton It's does not recognize it.

Singleton implementation:

    public class DatabaseConnection {
        private static DatabaseConnection dbIsntance = null;
        private static Connection con;
    
        private DatabaseConnection() {}
    
        public static DatabaseConnection getInstance() {
            if (dbIsntance == null) {
                dbIsntance = new DatabaseConnection();
            }
            return dbIsntance;
        }
    
        public Connection getConnection() throws Exception {
            if (con == null || con.isClosed()) {
                String url = "jdbc:mysql://localhost:3306/";
                String dbName = "db";
                String driver = "com.mysql.jdbc.Driver";
                String userName = "root";
                String password = "";
    
                Class.forName(driver).newInstance();
                con = DriverManager.getConnection(url + dbName, userName, password);
            }
            return con;
        }
    }

Model class:

public class User {
        private int id;
        private String username;
        private String password;
    
        
    
        public void saveOrUpdate(){
            Connection con = null;
            try {
                con = DatabaseConnection.getInstance().getConnection();
                PreparedStatement stmt = con.prepareStatement("insert into users (`username`, `password`) values (?,?)");
                stmt.setString(1, this.username);
                stmt.setString(2, this.password);
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                if (con != null) {
                    con.close();
                }
            }
        }
    }

The Idea(Intelij) show me an error Cannot resolve symbol 'DatabaseConnection'

What I have did wrong?

Aucun commentaire:

Enregistrer un commentaire