CRUD with Spring MVC & Hibernate

4. Create Entity Class & Define Relationship Between Tables

In this part, we need to understand the ORM concept in computer software.

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.

If we are using the classic JDBC, the query result is in the ResultSet format. If we want to use it in our applications (which is object-oriented base), we need to do manual parsing. By using Hibernate, the query results is in object and collections format. We can directly use it in program without further parsing.

In the ORM process, you need to make a Java class corresponding with a table in database. In our previous example, we have two tables (Category and Product). So we need to create two Java class (Category.java and Product.java). A class that represents table in a database called entity class.

There are several considerations in the ORM process:

  • Data types
    Make sure that the data types between tables and Java class is compatible. For example:

    • TEXT or VARCHAR in table can be represented by String in Java class.
    • INTEGER in table can be represented by Integer, int in Java class.
    • DECIMAL, NUMBER, or other floating numbers can be represented by double, float, etc. in Java class.
    • Binary data types (blob, lob, etc.) can be represented by byte, or another raw data format.
  • Primary key constraint
    In entity class, primary key constraint represented by @Id annotations. If primary key is autonumber, we also add @GeneratedValue annotation.
  • Table column mapping.
    To represent a table column, a property in entity class must have @Column annotation.
  • Relationship
    In tables, relationship is represented by a foreign key. In one-to-many relationship, the destined tables always have foreign key from the parent table. In entity class, we need to represent this relationship using object and collections. We see a one-to-many relationship between Category and Product into two parts.

    • One-to-many from Category to Product
      It means that every Category have many Products. So in the Category, we will have a collection of Product. In entity class, we can use List or Collection and add @OneToMany annotation.
    • Many-to-one from Product to Category
      It means that every Product have one corresponding Category. So in the Product, we will have a Category object and add @ManyToOne annotation.

Here is the example of entity classes for the previous tables. Please make sure that you put this two class into domain package.

package org.munif.domain;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="category")
public class Category {
    @Id                         // represents that this field is primary key 
    @GeneratedValue             // represents that the primary key is autonumber
    @Column(name="categoryId")    // column annotation: it means this property is mapped to a table column
    private int categoryId;

<pre><code>@Column(name=&amp;quot;categoryName&amp;quot;)
private String categoryName;

@Column(name=&amp;quot;categoryDescription&amp;quot;)
private String categoryDescription;

// 1. FetchType.LAZY --&amp;gt; LAZY means the data will be loaded if needed.
// 2. Each category can have many products. Hence, we use List to represent it.
// 3. mappedBy = &amp;quot;category&amp;quot; --&amp;gt; &amp;quot;category&amp;quot; is a property in the Product.java class 
//    that binds the one-to-many relationships. It behaves like foreign key in Product class.
@OneToMany(fetch = FetchType.LAZY, mappedBy = &amp;quot;category&amp;quot;)
private List&amp;lt;Product&amp;gt; products;

public Category() {

}

public Category(String categoryName, String categoryDescription) {
    this.categoryName = categoryName;
    this.categoryDescription = categoryDescription;
}

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 getCategoryDescription() {
    return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
    this.categoryDescription = categoryDescription;
}
public List&amp;lt;Product&amp;gt; getProducts() {
    return products;
}

public void setProducts(List&amp;lt;Product&amp;gt; products) {
    this.products = products;
}

@Override
public String toString() {
    return &amp;quot;Category [categoryId=&amp;quot; + categoryId + &amp;quot;, categoryName=&amp;quot;
            + categoryName + &amp;quot;, categoryDescription=&amp;quot; + categoryDescription
            + &amp;quot;]&amp;quot;;
}
</code></pre>

}
package org.munif.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name=&quot;product&quot;)
public class Product {

<pre><code>@Id
@GeneratedValue
@Column(name=&amp;quot;productId&amp;quot;)
private int productId;

@Column(name=&amp;quot;productName&amp;quot;)
private String productName;

@Column(name=&amp;quot;productStock&amp;quot;)
private int productStock;

@Column(name=&amp;quot;productPrice&amp;quot;)
private double productPrice;

@Column(name=&amp;quot;productDescription&amp;quot;)
private String productDescription;

// 1. FetchType.LAZY --&amp;gt; LAZY means the data will be loaded if needed.
// 2. Each product always have a 'category'. Hence, we use a property with type 'Category'.
//    In Category.java, this properties is called by using : mappedBy = &amp;quot;category&amp;quot;
// 3. @JoinColumn(name=&amp;quot;categoryId&amp;quot;) --&amp;gt; defines foreign key in the table. 
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name=&amp;quot;categoryId&amp;quot;)
private Category category;

public Product() {
}

public Product(String productName, int productStock, double productPrice,
        String productDescription) {
    this.productName = productName;
    this.productStock = productStock;
    this.productPrice = productPrice;
    this.productDescription = productDescription;
}

public int getProductId() {
    return productId;
}
public void setProductId(int productId) {
    this.productId = productId;
}
public String getProductName() {
    return productName;
}
public void setProductName(String productName) {
    this.productName = productName;
}
public int getProductStock() {
    return productStock;
}
public void setProductStock(int productStock) {
    this.productStock = productStock;
}
public double getProductPrice() {
    return productPrice;
}
public void setProductPrice(double productPrice) {
    this.productPrice = productPrice;
}
public String getProductDescription() {
    return productDescription;
}
public void setProductDescription(String productDescription) {
    this.productDescription = productDescription;
}
public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}

@Override
public String toString() {
    return &amp;quot;Product [productId=&amp;quot; + productId + &amp;quot;, productName=&amp;quot;
            + productName + &amp;quot;, productStock=&amp;quot; + productStock
            + &amp;quot;, productPrice=&amp;quot; + productPrice + &amp;quot;, productDescription=&amp;quot;
            + productDescription + &amp;quot;]&amp;quot;;
}
</code></pre>

}
Advertisements

3 thoughts on “CRUD with Spring MVC & Hibernate

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s