1. 程式人生 > >Hibernate之CRUD操作

Hibernate之CRUD操作

package loaderman.b_crud;

import loaderman.a_hello.Employee;

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


public interface IEmployeeDao {

    void save(Employee emp);
    void update(Employee emp);
    Employee findById(Serializable id);
    List<Employee> getAll();
    List
<Employee> getAll(String employeeName); List<Employee> getAll(int index, int count); void delete(Serializable id); }
package loaderman.b_crud;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
public
class App_ddl { // 自動建表 @Test public void testCreate() throws Exception { // 建立配置管理類物件 Configuration config = new Configuration(); // 載入主配置檔案 config.configure(); // 建立工具類物件 SchemaExport export = new SchemaExport(config); // 建表
// 第一個引數: 是否在控制檯列印建表語句 // 第二個引數: 是否執行指令碼 export.create(true, true); } }
package loaderman.b_crud;

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

import loaderman.a_hello.Employee;
import loaderman.utils.HibernateUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;



public class EmployeeDaoImpl implements IEmployeeDao{

    @Override
    public Employee findById(Serializable id) {
        Session session = null;
        Transaction tx = null;
        try {
            // 獲取Session
            session = HibernateUtils.getSession();
            // 開啟事務
            tx = session.beginTransaction();
            // 主鍵查詢
            return (Employee) session.get(Employee.class, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public List<Employee> getAll() {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            // HQL查詢
            Query q = session.createQuery("from Employee");
            return q.list();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public List<Employee> getAll(String employeeName) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query q =session.createQuery("from Employee where empName=?");
            // 注意:引數索引從0開始
            q.setParameter(0, employeeName);
            // 執行查詢
            return q.list();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public List<Employee> getAll(int index, int count) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query q = session.createQuery("from Employee");
            // 設定分頁引數
            q.setFirstResult(index);  // 查詢的其實行
            q.setMaxResults(count);      // 查詢返回的行數

            List<Employee> list = q.list();
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public void save(Employee emp) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            // 執行儲存操作
            session.save(emp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }

    }

    @Override
    public void update(Employee emp) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            session.update(emp);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }

    }

    @Override
    public void delete(Serializable id) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            // 先根據id查詢物件,再判斷刪除
            Object obj = session.get(Employee.class, id);
            if (obj != null) {
                session.delete(obj);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }
}
package loaderman.a_hello;

import java.util.Date;

public class Employee {

    private int empId;
    private String empName;
    private Date workDate;
    
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public Date getWorkDate() {
        return workDate;
    }
    public void setWorkDate(Date workDate) {
        this.workDate = workDate;
    }
    @Override
    public String toString() {
        return "Employee [empId=" + empId + ", empName=" + empName
                + ", workDate=" + workDate + "]";
    }
    
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="loaderman.a_hello">
    
    <class name="Employee" table="employee">
        
        <!-- 主鍵 ,對映-->
        <id name="empId" column="id">
            <generator class="native"/>
        </id>
        
        <!-- 非主鍵,對映 -->
        <property name="empName" column="empName"></property>
        <property name="workDate" column="workDate"></property>
        
    </class>

</hibernate-mapping>

 

package loaderman.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

    private static SessionFactory sf;
    static {
        // 載入主配置檔案, 並建立Session的工廠
        sf = new Configuration().configure().buildSessionFactory();
    }

    // 建立Session物件
    public static Session getSession(){
        return sf.openSession();
    }
}