Hibernate-简单的crud案例
来源:互联网 发布:php二进制转换字符串 编辑:程序博客网 时间:2024/06/08 06:34
一.导包
二.写总配置文件 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-182 jhon 2008-03-193 tim 2008-03-194 ooo 2013-04-105 cx 2008-03-196 eee22 2013-04-097 dedede 2009-04-308 abc 2009-04-309 eqwe 2009-04-3010 qwqwqw 2009-04-3011 ssdada 2009-04-3012 wqeqe 2009-04-2313 weqeqwewqe 2009-04-2314 abc 2009-04-3015 weqrq 2009-04-3016 cxspace 2009-04-2317 2132131 2009-04-3018 wtewtrt 2009-04-3019 eqrqrq 2009-04-3020 rwqrerq 2009-04-2321 aaasadad 1330-02-1922 小明 2016-07-1623 小华 2016-07-1628 奥巴马
0 0
- Hibernate-简单的crud案例
- hibernate简单的crud
- Hibernate实现简单的CRUD
- Hibernate 入门------简单的CRUD
- 基于JPA的Hibernate->CRUD(简单应用)
- hibernate之crud小案例
- Hibernate-CRUD简单实例
- Hibernate-简单完成crud
- Hibernate入门BLOG [四、Hibernate的CRUD简单总结]
- maven hibernate 实现对mysql简单的CRUD操作
- hibernate 的CRUD
- hibernate的crud操作
- hibernate的CRUD操作
- hibernate的CRUD操作
- Hibernate的CRUD操作
- hibernate的crud操作
- Hibernate的基本CRUD
- Hibernate的CRUD
- Hibernate学习-2-环境搭建
- Hibernate学习-3-API详解以及执行流程
- container_of分析
- 解构C#游戏框架uFrame兼谈游戏架构设计
- Hibernate学习-4-各种查询方式
- Hibernate-简单的crud案例
- Hibernate学习-5-配置文件详解
- Hibernate-复合主键案例
- Hibernate学习-6-集合映射保存和集合数据获取案例
- Hibernate学习-7-关联映射(一对多,多对一)
- Hibernate学习-7-关系映射(多对多)
- JAVA之旅(三十四)——自定义服务端,URLConnection,正则表达式特点,匹配,切割,替换,获取,网页爬虫
- Hibernate学习-8-缓存,懒加载
- Hibernate学习-9-一对一映射