Friday, July 29, 2011

HIBERNATE Examples - Step 3. Simple CUD operations

The following example takes you through the Create Update Delete operations on a simple persistent object.

Departments.java

package org.mybusiness.pojos;

import java.io.Serializable;

public class Departments implements Serializable {

    private int deptId;

    private String deptName;

    private String yearStarted;

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public String getYearStarted() {
        return yearStarted;
    }

    public void setYearStarted(String yearStarted) {
        this.yearStarted = yearStarted;
    }
}

DepartmentsDao.java

package org.mybusiness.daos;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.mybusiness.pojos.Departments;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class DepartmentDao {

    private SessionFactory sessionFactory;

    public DepartmentDao(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public boolean addDepartment(Departments department) {

        HibernateTemplate ht = new HibernateTemplate(sessionFactory);
        Serializable s = ht.save(department);
        System.out.println("Primary Key: " + s);
        return true;
    }

    public boolean deleteDepartment(Departments department) {

        HibernateTemplate ht = new HibernateTemplate(sessionFactory);
        ht.delete(department);
        return true;
    }
}

No comments:

Post a Comment