Hi.
I am having problems connecting and the use of DAO Could someone start me off to find problems that
are conceptionally wrong with the structure?
error

if the connection is made and database is built (DerbyDAO) then the InstructorDao SHOULD become JDBCSchoolofdbDAO and return "profile" which will allow the program to collect data and GUI WILL BUILD
accordingly.
note: there is no password constrainst at all yet No connection yet.


ok cancel assuming profile is for instructor

String message = "Please enter your user name and password.";
        int result = JOptionPane.showOptionDialog(frame, new Object[]{stu, instr, admin, pay, message, userLbl, userField, passLbl, passField},
                "Login", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);

        if (result == JOptionPane.OK_OPTION) {

            String user = userField.getText().trim();
            char[] password = passField.getPassword();
            String profile = getprofile();
            
            LoginInfoBean lib = new LoginInfoBean();
            String connected = lib.loginAction(user, password,profile);
            //lib.loginAction is in LoginInfoBean.java
            //if this connects and builds db and tables then it is connected
            //JDBCSchoolofdbDAO which useses DerbyDAO to do the latter.
            //and in theory should build a new model of the specific profile.
                if (connected.equals("profile")) {

                    try {
                        createNewGuide(desktopName);
                    } catch (IOException ex) {
                        Logger.getLogger(SchoolJDesktopPane.class.getName()).log(Level.SEVERE, null, ex);
                    }      
                    
                }
           
            try {

                if (connected.equals("not connected")) {
                } else {
                    throw new LoginException();
                }

            } catch (LoginException e) {
                String x = e.getMessage();
               
                ViewUtils vu = new ViewUtils();
                vu.addExceptionMessage(x);

            }

        }
        if (result == JOptionPane.CANCEL_OPTION) {
        continued............

InstructorDAO.JAVA

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model.dao;
import model.LoginInfo;
import model.InstructorUser;
import model.err.IncorrectPasswordException;
import model.err.LoginException;
import model.err.ProfileException;
import model.err.SubscribeException;
import model.err.UnsubscribeException;
/**
 *
 * @author depot
 */
public interface InstructorDAO {
    public InstructorUser select(LoginInfo loginInfo)
            throws LoginException,
            //UnknowninstructorUserException,
            IncorrectPasswordException;

    public void insertInstructor(InstructorUser instructorUser)
            throws SubscribeException;

    public void update(InstructorUser instructorUser)
            throws ProfileException;

    public void delete(InstructorUser instructorUser)
            throws UnsubscribeException;
}
continued.............

ModelResources.properties

# To change this template, choose Tools | Templates
# and open the template in the editor.

DAO=model.dao.JDBCSchoolofdbDAO

# Sample ResourceBundle properties file

derby.driver=org.apache.derby.jdbc.EmbeddedDriver
derby.url=jdbc:derby:
db.table=ADDRESS
db.schema=APP
continued............

LoninInfoBean.java

public String loginAction(String userName, char[] password, String profile) {
        this.userName = userName;
        this.password = password.toString();
        this.profile = profile;


continued............

 if (profile.equals("instr_")) {
            InstructorUser instructorModel = new InstructorUser();
            try {
                InstructorBean instrBean = (InstructorBean) ModelUtils.getInstructorUserDAO();
                instrBean.setLoggedIn(true);
                ModelUtils.copy(instrBean, instructorModel);
            } catch (Exception e) {
                return null;
            }

            return "profile";

        }
continued...............
continued........
public synchronized static InstructorDAO getInstructorUserDAO() {
        if (instructorDAO == null)
            try {
                Class daoClass = Class.forName(getResource("DAO"));
                instructorDAO
                    = (InstructorDAO) daoClass.newInstance();
            } catch (ClassNotFoundException x) {
                log(x);
                throw new InternalError(x.getMessage());
            } catch (IllegalAccessException x) {
                log(x);
                throw new InternalError(x.getMessage());
            } catch (InstantiationException x) {
                log(x);
                throw new InternalError(x.getMessage());
            }
        return instructorDAO;
    }
continued.........

JDBCSchoolofdbDAO.java (each profile can become this class

public JDBCSchoolofdbDAO() {
        DerbyDAO db = new DerbyDAO();
        System.out.println(db.getDatabaseLocation());
        System.out.println(db.getDatabaseUrl());
        //db.disconnect();
        conn=null;
        Connection conn = db.getConn();
        setConn(conn);
    }

    private void close(Connection conn, PreparedStatement ps)
            throws SQLException {
        if (ps != null) {
            ps.close();
        }
        if (conn != null) {
            conn.close();
        }
        // this is calling derbyDAO to disconnect
        db.disconnect();
    }
//////////////////////////////////////////////////////////////////////
    //////////////////  login find user /////////////////////////
    ////////////////////////////////////////////////////////////////

    public Object select(LoginInfo loginInfo)
            throws LoginException,
            UnknownSubscriberException,
            IncorrectPasswordException {


        Connection conn = getConn();
        PreparedStatement ps = null;
        try {
            //conn = dataSource.getConnection();
            ps = conn.prepareStatement(
                    ModelUtils.getResource("SelectUserGroup"));
            //ps.setString(1, loginInfo.getEmail());
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                throw new UnknownSubscriberException();// no exceptions are good
            }

            String groupName = rs.getString(1);

continued............
 if (groupName.equals("instructor")) {
                setType("instructor");

                InstructorUser instructorUser = selectInstructor();

                newUser = instrUser;


            }
continued..........

DerbyDAO.JAVA I needed to build an imbedded db using MySQL db

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao;
//import com.sun.demo.addressbook.Address;
//import com.sun.demo.addressbook.ListEntry;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.util.Properties;
import javax.activation.DataSource;
import model.ModelUtils;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import model.LoginInfo;
import model.AdminUser;
import model.InstructorUser;
import model.PayeeUser;
import model.StudentUser;

/**
 *
 * @author depot
 */
public class DerbyDAO {

    /** Creates a new instance of DerbyDAO */
    private Connection conn;
    private Properties dbProperties;
    private boolean isConnected;
    private String dbName;
    private String stmtCreateAdminTable;
    private String stmtCreateBookingTable;
    private String stmtCreateInstrAvailableTable;
    private String stmtCreateInstructorTable;
    private String stmtCreateInstrumentTable;
    private String stmtCreateLocationTable;
    private String stmtCreatePayeeTable;
    private String stmtCreatePaymentTable;
    private String stmtCreatePayRollTable;
    private String stmtCreateStudentTable;
    private String stmtCreateUserTable;
    private String stmtCreateUserGroupTable;
    private String stmtCreateUserGroupMappingTable;
    private String[] schoolofdbTables = {
        " strCreateAdminTable",
        " strCreateBookingTable",
        " strCreateInstrAvailableTable",
        " strCreateInstructorTable",
        " strCreateInstrumentTable",
        " strCreateLocationTable",
        " strCreatePayeeTable",
        " strCreatePaymentTable",
        " strCreatePayRollTable",
        " strCreateStudentTable",
        " strCreateUserTable",
        " strCreateUserGroupTable",
        " strCreateUserGroupMappingTable",};
    private boolean bCreatedTables;
    /*
    private PreparedStatement stmtSaveNewRecord;
    private PreparedStatement stmtUpdateExistingRecord;
    private PreparedStatement stmtGetListEntries;
    private PreparedStatement stmtGetAddress;
    private PreparedStatement stmtDeleteAddress;
     * 
     */
    private DataSource dataSource;
    private String type;
    private LoginInfo loginInfo;
    private Object newUser;
    private AdminUser adminUser;
    private InstructorUser instrUser;
    private PayeeUser payeeUser;
    private StudentUser studentUser;
    private StudentUser thisStudentUser;
    private InstructorUser thisInstructortUser;
    private AdminUser thisAdminUser;
    private PayeeUser thisPayeeUser;
    private PreparedStatement ps;
    

    public DerbyDAO() {
        this("schoolofdb");
    }

    public DerbyDAO(String schoolofdb) {
        this.dbName = schoolofdb;

        setDBSystemDir();
        dbProperties = loadDBProperties();
        String driverName = dbProperties.getProperty("derby.driver");
        loadDatabaseDriver(driverName);
        if (!dbExists()) {
            createDatabase();
        }
    }
    public boolean connect() {
        String dbUrl = getDatabaseUrl();
        try {
            conn = DriverManager.getConnection(dbUrl, dbProperties);
            isConnected = conn != null;
            setConn(conn);
        } catch (SQLException ex) {
            isConnected = false;
        }
        return isConnected;
    }
    

    private boolean dbExists() {
        boolean bExists = false;
        String dbLocation = getDatabaseLocation();
        File dbFileDir = new File(dbLocation);
        if (dbFileDir.exists()) {
            bExists = true;
        }
        return bExists;
    }

    private void setDBSystemDir() {
        // decide on the db system directory
        String userHomeDir = System.getProperty("user.home", ".");
        String systemDir = userHomeDir + "/.schoolofdb";
        System.setProperty("derby.system.home", systemDir);

        // create the db system directory
        File fileSystemDir = new File(systemDir);
        fileSystemDir.mkdir();
    }

    private void loadDatabaseDriver(String driverName) {
        // load Derby driver
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

    }

    private Properties loadDBProperties() {
        InputStream dbPropInputStream = null;
        dbPropInputStream = DerbyDAO.class.getResourceAsStream("ModelResources.properties");
        dbProperties = new Properties();
        try {
            dbProperties.load(dbPropInputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return dbProperties;
    }

   
    private boolean createDatabase() {
        boolean bCreated = false;
        Connection conn = null;
        String dbUrl = getDatabaseUrl();
        dbProperties.put("create", "true");

        try {
            conn = DriverManager.getConnection(dbUrl, dbProperties);
            bCreated = createTables(conn);
        } catch (SQLException ex) {
        }
        dbProperties.remove("create");
        return bCreated;
    }
     private boolean createTables(Connection conn) {
        for (int i = 0; i < schoolofdbTables.length; i++) {
            boolean bCreatedTables = false;
            PreparedStatement ps = null;
            try {
                ps = (PreparedStatement) conn.prepareStatement(
                        ModelUtils.getResource(schoolofdbTables[i]));
                ps.executeQuery();
                bCreatedTables = true;
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return bCreatedTables;
    }

    private String getHomeDir() {
        return System.getProperty("user.home");
    }

    private void close(Connection conn, PreparedStatement ps)
            throws SQLException {
        if (ps != null) {
            ps.close();
        }
        if (conn != null) {
            conn.close();
        }
    }

    public void disconnect() {
        if (isConnected) {
            String dbUrl = getDatabaseUrl();
            dbProperties.put("shutdown", "true");
            try {
                DriverManager.getConnection(dbUrl, dbProperties);
            } catch (SQLException ex) {
            }
            isConnected = false;
        }
    }
    public static void main() {
        
    }
    
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Object getNewUser() {
        return newUser;
    }

    public void setNewUser(Object newUser) {
        this.newUser = newUser;
    }

    public String getDatabaseLocation() {
        String dbLocation = System.getProperty("derby.system.home") + "/" + dbName;
        return dbLocation;
    }

    public String getDatabaseUrl() {
        String dbUrl = dbProperties.getProperty("derby.url") + dbName;
        return dbUrl;
    }

    public Connection getConn() {
        return conn;
    }

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


   
    
   
}

It kind of seems clunky and complicated at best. A couple of questions:

  • What do you achieve by dynamically loading your DAO class?
  • Why is your DAO throwing business exceptions? I'm pretty sure I have at some point in time replied to your post in the JSP section and asked you not to do so.
  • Why progamatically create database tables? Table creation/data population scripts are much more logical unless you have some weird requirement in which case you might want to mention that.

Your data access layer should be as simple as possible, really. Having loads of exception handling, connection management logic isn't good. You have two ways of improving your JDBC code quality:

  • Either create a mini framework which manages connections/transactions for DAO's
  • Use an existing framework and be done with it
commented: N/A +9

It kind of seems clunky and complicated at best. A couple of questions:

  • What do you achieve by dynamically loading your DAO class?
  • Why is your DAO throwing business exceptions? I'm pretty sure I have at some point in time replied to your post in the JSP section and asked you not to do so.
  • Why progamatically create database tables? Table creation/data population scripts are much more logical unless you have some weird requirement in which case you might want to mention that.

Your data access layer should be as simple as possible, really. Having loads of exception handling, connection management logic isn't good. You have two ways of improving your JDBC code quality:

  • Either create a mini framework which manages connections/transactions for DAO's
  • Use an existing framework and be done with it

I am just trying to understand how DAO works for now I will apreciate you input and will consider all those possibilities

What do you achieve by dynamically loading your DAO class?
At this point in "theory" I was trying to use one model for each student,instructor,payee,admin. which ever one logs in could access the db and copy data back to its model.

Why progamatically create database tables? Table creation/data population scripts are much more logical unless you have some weird requirement in which case you might want to mention that.

I built a MySQL database and now I had to learn how to use an embedded db and the Derby info I have seen prescribed a similar procedure.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.