SQL – Handling Database Foreign Keys in Entity Classes

attributesobject-orientedsql

I know that an attribute defines the state of an object. So, is it correct to keep attributes that don't define the state of an object of a class?

For example, I have an Employee class, which has these attributes:

emp_id,
fname,
lname,
mname,
salary,
mobile,
email,
gender,
maritalstatus,
position,
birthdate,
hiredate,
dept_id,
address_id,
bank_id.

The dept_id, address_id and bank_id are foreign keys. Now my actual question is can we include attributes like bank_id, address_id and dept_id into Employee class because they are not actually showing exact behavior of Employee Class? Instead can I make another class named EmployeeForeignKeys and keep these attributes bank_id, address_id, dept_id in that class?

Best Answer

First a couple of observations:

  1. Classes don't have foreign keys. You are assuming classes represent tables in a relational database and that's wrong. Not every class in the world will be persisted to a RDBMS, nor every RDBMS table will have a class modeled after it. That is wrong to begin with.
  2. How exactly do you tell what "defines the state" of an object and what doesn't? Perhaps for a Person class the BankAccount is not part of its inner state but for an Employee class it does.
  3. dept_id and address_id don't follow any widely accepted Java naming convention, they should be named deptId, addressID, etc.

An Employee class shouldn't have a bankID member but a bankAccount member which is of type BankAccount.

I wouldn't do this:

public class Employee{
    private int coBank;
    public int getCoBank(){};
}

but this

public class Employee{
    private BankAccount bankAccount;
    public BankAccount getBankAccount(){};
}

In the case of a person perhaps the banking information is not part of the class itself, so, you invert the logic so the person doesn't have a reference to the banking information and let the BankAccount have a reference to the person:

public class BankAccount{
    public Person owner getOwner(){};
}

In the case of en amployee, everyone should have a bank account to work properly so it makes sense the bank account to be part of its state.

In the case of a mere person that may not be so, so the bank account should reference the person and not the other way around.

EDIT:

@COMEFROM in one comment added some valid exceptions to my point on whether or not classes should have referencing IDs as members:

I think it's worth to mention that having referencing ID:s as attributes is alright in a larger scale, if the referenced entity is out of the scope of the system under design or if it otherwise belongs to some other context than the parent object.

Related Topic