简体   繁体   中英

Good practice to store derived classes in the database

I'm writing a simple java application (in study purpose) to manage employees and I need an advise: how to store and retrieve data from the database.

Code, that I have wrote so far is too big to put it here, so, in two words:

I have next hierarchy: abstract class Employee: 4 attributes, getters, setters class Salaried: 2 new attribute class Hourly : 2 new attributes class Director: 3 new attributes class Manager : 1 new attribute

I have a MySQL data with 1 table (create script):

CREATE TABLE `employee` (
  `SSN` int(9) NOT NULL PRIMARY KEY,
  `FirstName` varchar(20) NOT NULL,
  `LastName` varchar(20) NOT NULL,
  `Department` varchar(20) NOT NULL,
  `Salary` float(10) NULL,
  `OvertimeHours` float(10) NULL,
  `HourlyWage` float(10) NULL,
  `NumberHours` float(10) NULL,
  `Organization` varchar(30) NULL,
  `Bonus` float(10) NULL
);

First 4 fields are general for all employees.

Salary and OvertimeHours are attributes of the Salaried class

HourlyWage and NumberHours are attributes of the Hourly class

Salary , Bonus and Organization are attributes of the Director class

Salary also is a attribute of the Manager class

I've created a static class Database to work with the MySQL.

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;


public abstract class Database {
    // constants
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String DBNAME = "records";
    private static final String DBUSER = "root";
    private static final String DBPASS = "";
    private static final String CONURL = "jdbc:mysql://localhost/" + DBNAME;

    // class attributes
    private static Connection connection = null;


    public static boolean fillEmployee(Employee emp, int ssn)
    {
        try {
            PreparedStatement stm = connection.prepareStatement(
                "SELECT FirstName, LastName, Department "
              + "FROM employee "
              + "WHERE SSN = ?"
            );

            stm.setInt(1, ssn);

            ResultSet rs = stm.executeQuery();

            if(!rs.next())
                return false;

            emp.setSocialSecurity(ssn);
            emp.setFirstName(rs.getString("FirstName"));
            emp.setLastName(rs.getString("LastName"));
            emp.setDepartment(rs.getString("Department"));

            stm.close();
            rs.close();

        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        return true;
    }


    public static boolean deleteEmployee(int ssn){
        try {
            PreparedStatement stm = connection.prepareStatement(
                "DELETE "
              + "FROM employee "
              + "WHERE SSN = ?"
            );

            stm.setInt(1, ssn);
            return (stm.executeUpdate() == 1);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        return false;
    }


    // class methods
    public static Salaried getSalariedEmployee(int ssn){
        Salaried employee = new Salaried();
        try {

            if(!fillEmployee(employee, ssn))
                return null;

            PreparedStatement stm = connection.prepareStatement(
                "SELECT Salary, OvertimeHours "
              + "FROM employee "
              + "WHERE SSN = ?"
            );

            stm.setInt(1, ssn);
            ResultSet rs = stm.executeQuery();

            employee.setSalary(rs.getFloat("Salary"));
            employee.setOvertimeHours(rs.getFloat("OvertimeHours"));

            stm.close();
            rs.close();

        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(0);
        }
        return employee;
    }

    public static void createConnection() {
        if (connection !=  null) 
            return;

        try {

            Class.forName(DRIVER);
            connection = DriverManager.getConnection(CONURL, DBUSER, DBPASS);

        } catch (Exception e) {

            System.out.println(e.getMessage());
            System.exit(0);

        }
    }

    public static void closeConnection(){
        if (connection == null) 
            return;

        try{

            connection.close();
            connection = null;

        } catch (Exception e) {

            System.out.println(e.getMessage());
            System.exit(0);

        }
    }
}

What are you thinking about getSalariedEmployee and fillEmployee methods? How can I improve the overall design and architecture of my application?

I think you could wait for creating the employee object in getSalariedEmployee. instantiate it only if you find the db object. Because if you return null when not finding it, you still create the employee object.

Perhaps you should start with a good reading of the book Patterns of Enterprise Architecture . It has a good chapter covering the different ways in which we typically deal with the database.

You can read quick definitions of these in the companion web site:

All the patterns have advantages and disadvantages and some of them have entire frameworks that help you write code for them.

The first thing I would do is stop using static methods for all your Database functions. Also why is Database an abstract class? Is there another class that extends Database with specific implementations (like MyDatabase or OracleDatabase.

You might consider using static methods to return an instance of a Database and then convert the static methods to public instance methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM