Model Review

A Category model class has a private field, a getter and a setter for each column of the categories table.

Journeyman · Java · SQL · Updated

By

In Creating Data Models, in the Encapsulation chapter, we created a class for a Category model. This model matches the data that is stored in each row of the categories table.

The categories table (category_id int, category_name varchar(15), description text) beside the UML Category class, which has a matching private field, getter and setter for each column

Example

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 Product model

The products page needs Northwind's products as Java objects, so it needs a model for the products table, the way Category models categories. Here are the columns it uses, and the variable each one becomes. A whole-number column is an int, text is a String, and a price with decimal places is a double:

Column SQL type Variable in the model
product_id int productId, an int
product_name varchar(40) productName, a String
unit_price decimal(10,4) unitPrice, a double
units_in_stock smallint unitsInStock, an int

For example, Chai's row is 1, Chai, 18.00, 39. Its object is filled like this:

Product product = new Product();
product.setProductId(1);
product.setProductName("Chai");
product.setUnitPrice(18.0);
product.setUnitsInStock(39);

After those four calls, the getters give back 1, "Chai", 18.0 and 39.

Your job: finish the class Product. 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 product 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