Hibernate-简单的crud案例

一.导包

二.写总配置文件 hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
         <!--数据库连接配置-->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///learnstruts</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">33269456.cx</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <!--加载所有映射-->
        <mapping resource="com/cx/hello/Employee.hbm.xml"></mapping>
    </session-factory>

</hibernate-configuration>

三.写entity类

package com.cx.hello;

import java.util.Date;

/**
 * Created by cxspace on 16-7-16.
 */
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 +
                '}';
    }
}

四,编写对象关系配置文件  Employee.hbm.xml

<?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="com.cx.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>

五.编写接口com.cx.crud.IEmployeeDao

package com.cx.crud;
import com.cx.hello.Employee;
import java.io.Serializable;
import java.util.List;

/**
 * Created by cxspace on 16-7-19.
 */
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 com.cx.crud;

import com.cx.hello.Employee;
import com.cx.utils.HibernateUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

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

/**
 * Created by cxspace on 16-7-19.
 */
public class EmployeeDao implements IEmployeeDao {


    @Override
    public void save(Employee emp) {

        Session session = null;
        Transaction tx = null;

        try {
            //获取session
            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
            session = HibernateUtils.getSession();
            //开启事务
            tx = session.beginTransaction();

            session.update(emp);

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

    }

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

        }

    }
}

session获取工具类

package com.cx.utils;

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

/**
 * Created by cxspace on 16-7-19.
 */
public class HibernateUtils {


    private static SessionFactory sf;

    static {
        //加载主配置文件,并创建session对象
        sf = new Configuration().configure().buildSessionFactory();
    }

    public static Session getSession(){
        return sf.openSession();
    }

}

 

七.编写测试

package com.cx.test;

import com.cx.crud.EmployeeDao;
import com.cx.hello.Employee;

/**
 * Created by cxspace on 16-7-23.
 */
public class Test {

    private EmployeeDao employeeDao = new EmployeeDao();

    @org.junit.Test
    public void testsave(){
        Employee employee = new Employee();

        employee.setEmpName("奥巴马");

        employeeDao.save(employee);
    }


    public void testupdate(){

        Employee employee =new Employee();

        //更新必须设置主键
        employee.setEmpId(24);

        employee.setEmpName("new奥巴吗");

        employeeDao.update(employee);
    }


    public void testfindById(){
        System.out.println(employeeDao.findById(1));
    }

    public void testgetAll(){
        System.out.println(employeeDao.getAll());
    }



    public void testgetByname(){
        System.out.println(employeeDao.getAll("张三"));
    }


    public void testgetAllfenye(){
        System.out.println(employeeDao.getAll(0,2));
    }


    public void delete(){

        employeeDao.delete(27);

    }

}

附:数据库脚本

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `empName` varchar(20) DEFAULT NULL,
  `workDate` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8

测试数据

1    张三    2016-07-18
2    jhon    2008-03-19
3    tim    2008-03-19
4    ooo    2013-04-10
5    cx    2008-03-19
6    eee22    2013-04-09
7    dedede    2009-04-30
8    abc    2009-04-30
9    eqwe    2009-04-30
10    qwqwqw    2009-04-30
11    ssdada    2009-04-30
12    wqeqe    2009-04-23
13    weqeqwewqe    2009-04-23
14    abc    2009-04-30
15    weqrq    2009-04-30
16    cxspace    2009-04-23
17    2132131    2009-04-30
18    wtewtrt    2009-04-30
19    eqrqrq    2009-04-30
20    rwqrerq    2009-04-23
21    aaasadad    1330-02-19
22    小明    2016-07-16
23    小华    2016-07-16
28    奥巴马    

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值