Understanding Hibernate

Suppose we have simple message board that contain three classes

messageboarddb1

If we using JDBC, we have to maintain the relationship between Topic and Post manually,  but if we use Hibernate, hibernate will do it for us.

The Steps To Using Hibernate

  1. Create object model (POJO) for the class
  2. Configure the mapping file, this is connector between your database schema with your POJO
  3. Build database schema
  4. Configure hibernate

Step 1.

We create POJO for the class (Topic class, Post class and User class)

package discussion

import java.util.*;

public class User{
    private String id =null;
    private String password = null;
    /**
    * we need constructor without parameter
    * because hibernate needed
    */
    public User(){}
    public User(String id, String password){
        this.id=id;
        this.password=password;
    }

    public String getId(){
        return id;
    }
    public void setId(String id){
        this.id=id;
    }
    public String getPassword(){
        return password;
    }
    public void setPassword(String password){
        this.password=password;
    }
}

/**
* Topic class
*/

public class Topic{
    private String id=null;
    private Date timestamp=new Date();
    private Date modified = new Date();
    private List posts = new ArrayList();
    public Topic(){}
    public String getId(){ return id; }
    public void setId(String id){ this.id =id; }
    public Date getTimestamp(){ return timestamp; }
    public void setTimestamp(Date timestamp){this.timestamp=timestamp;}
    public Date getModified(){ return modified;}
    public void setModified(Date modified){this.modified=modified;}
    public List getPosts(){retun posts;}
    public void setPosts(List p){this.posts=p;}
}

/**
* Class Topic
*/
public class Post{
    private Long id;
    private String subjct;
    private String text;
    private User user;
    public Post(){}

    public String getId(){ return id; }
    public void setId(String id){ this.id =id; }
    public Date getTimestamp(){ return timestamp; }
    public void setTimestamp(Date timestamp){this.timestamp=timestamp;}
    public Date getModified(){ return modified;}
    public void setModified(Date modified){this.modified=modified;}
    public List getPosts(){retun posts;}
    public void setPosts(List p){this.posts=p;}
}

After finished, then create mapping. The mapping will be describe in chapter 2