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();
    }
}

 

posted on 2018-11-29 10:51  LoaderMan  阅读(152)  评论(0编辑  收藏  举报

导航