Creating Data Models

A data model class mirrors a database table, with a private variable and a getter and setter for each column.

Journeyman · Java · OOP · Updated

By

It is common to create classes that represent "models" of the data that is stored in a database. Models often have a 1-to-1 mapping of the columns of a table in the database.

The Category Class

Following is an example of what a Category class could look like in a Java application.

public class Category
{
    private int categoryId;
    private String categoryName;
    private String description;

    public int getCategoryId()
    {
        return categoryId;
    }
    public void setCategoryId(int categoryId)
    {
        this.categoryId = categoryId;
    }

    public String getCategoryName()
    {
        return categoryName;
    }
    public void setCategoryName(String categoryName)
    {
        this.categoryName= categoryName;
    }

    public String getDescription()
    {
        return description;
    }
    public void setDescription(String description)
    {
        this.description= description;
    }

}

Do it: write the Shipper model

The shipping page needs Northwind's shippers as Java objects, so it needs a model for the shippers table, the way Category models categories. Here are the table's columns and the variable each one becomes:

Column SQL type Variable in the model
shipper_id int shipperId, an int
company_name varchar(40) companyName, a String
phone varchar(24) phone, a String

For example, the first row is 1, Speedy Express, (503) 555-9831. Its object is filled like this:

Shipper shipper = new Shipper();
shipper.setShipperId(1);
shipper.setCompanyName("Speedy Express");
shipper.setPhone("(503) 555-9831");

After those three calls, shipper.getShipperId() returns 1, shipper.getCompanyName() returns "Speedy Express" and shipper.getPhone() returns "(503) 555-9831".

Your job: finish the class Shipper. Its getters and setters are there, with empty bodies.

  • Add a private variable for each column, with the name and type in the table.
  • Each getter returns its variable.
  • Each setter copies its parameter into its variable.
  • Each shipper keeps its own values: setting one doesn't change another.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets