Hibernate的增删改查CRUD

来源:互联网 发布:软件著作权怎么加急 编辑:程序博客网 时间:2024/06/11 22:22

Hibernate的增删改查 CRUD

  步骤一:

  在进行Hibernate的任何操作之前我们必须要做的步骤。(以下步骤在Hibernate的第一个小例子中有详解)

  1.导包(这里需要导入9个基础包)。

  2.建立与数据库项对应的实体对象类Employee

  3.编写实体类相对应的映射文件Employee.hbm.xml(要与Employee在同一目录下)

  4.编写hibernate.cfg.xml主配置文件(在其中进行数据库连接的配置,以及映射文件的配置)

 

步骤二: 

 我们需要建立一个进行crud的接口类IEmployee,在其中写好crud方法。

  结构展示




步骤三:

我们建立一个接口IEmployee 的实现类 接口类EmployeeDaoImpl ,在其中实现crud的具体操作。

package cn.itcast.b_crud;import java.io.Serializable;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import cn.itcast.a_hello.Employee;import cn.itcast.utils.HibernateUtils;public class EmployeeDaoImpl implements IEmployeeDao{    //进行添加操作@Overridepublic void save(Employee employee) {Session session=null;Transaction tx=null;try {session=HibernateUtils.getSession();//获取Sessiontx=session.beginTransaction();//开启事务session.save(employee);} catch (Exception e) {   throw new RuntimeException(e);}finally{tx.commit();session.close();}}   //进行删除操作@Overridepublic void delete(Serializable id) {Session session=null;Transaction tx=null;try {session=HibernateUtils.getSession();//获取Sessiontx=session.beginTransaction();//开启事务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();}} //进行修改操作@Overridepublic void update(Employee employee) {Session session=null;Transaction tx=null;try {session=HibernateUtils.getSession();//获取Sessiontx=session.beginTransaction();//开启事务session.update(employee);} catch (Exception e) {   throw new RuntimeException(e);}finally{tx.commit();session.close();}}//进行查询操作(直接查询所有)@Overridepublic List<Employee> getAll() {Session session=null;Transaction tx=null;try {session=HibernateUtils.getSession();//获取Sessiontx=session.beginTransaction();//开启事务//HQL查询(不支持*)Query q=session.createQuery("from Employee");return (List<Employee>)q.list();} catch (Exception e) {   throw new RuntimeException(e);}finally{tx.commit();session.close();}}//进行查询操作(通过传入employeeName进行查询)@Overridepublic List<Employee> getAll(String employeeName) {Session session=null;Transaction tx=null;try {session=HibernateUtils.getSession();//获取Sessiontx=session.beginTransaction();//Query q=session.createSQLQuery("select * from employee where empName="+employeeName); Query q=session.createQuery("from Employee where empName=?");//注意这里的Employee和empName都是实体类中的对象属性不是数据库中的 q.setParameter(0, employeeName);  //当不知道属性类型时就用setParameter()第二个参数是Object类型,参数索引从0开始 return (List<Employee>)q.list();  //执行查询} catch (Exception e) {   throw new RuntimeException(e);}finally{tx.commit();session.close();}}//进行分页查询操作(通过传入起始的位置,以及每页显示的对象数量)@Overridepublic List<Employee> getAll(int index, int count) {// 分页查询Session session=null;Transaction tx=null;try {session=HibernateUtils.getSession();//获取Sessiontx=session.beginTransaction();Query q=session.createQuery("from Employee");//不能在里面直接写Limit因素HQL查询是全对象的,支持任何数据库,而limit是mysql专用的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();}} //进行查询操作(通过传入id进行查询)@Overridepublic Employee findById(Serializable id) {Session session=null;Transaction tx=null;try {session=HibernateUtils.getSession();//获取Sessiontx=session.beginTransaction();//开启事务//主键查询return (Employee) (session.get(Employee.class, 1));} catch (Exception e) {   throw new RuntimeException(e);   //当你异常块中有返回值,却一直报错要你添加返回值时,只要在异常中抛出运行时异常即可解决。}finally{tx.commit();session.close();}}}



步骤四:

我们建立一个测试类TestApp ,对我们写好的crud进行测试。

小贴士:我们进行测试类的编写可以直接创建一个JUnit类,具体操作如下。





言归正传,我们还进行测试类的编写~


package cn.itcast.b_crud;import java.util.Date;import java.util.List;import org.junit.Test;import cn.itcast.a_hello.Employee;public class TestApp {private EmployeeDaoImpl empDao=new EmployeeDaoImpl();@Testpublic void testSave() {Employee emp=new Employee();         emp.setEmpName("小哈");         emp.setWorkDate(new Date()); empDao.save(emp);}@Testpublic void testUpdate() {Employee emp=new Employee();emp.setEmpId(2);        emp.setEmpName("美美");        emp.setWorkDate(new Date());//必须数据库中的字段值全设置        empDao.update(emp);}@Testpublic void testFindById() {System.out.println(empDao.findById(1));}@Testpublic void testGetAll() {System.out.println(empDao.getAll());}@Testpublic void testGetAllString() {empDao.getAll("哈哈");}@Testpublic void testGetAllIntInt() {System.out.println(empDao.getAll(2, 3));//因为索引从0开始,索引2指代的是数据库中的id值为3对应的数据,从id3开始后面三条数据}@Testpublic void testDelete() {empDao.delete(4);}}









原创粉丝点击