hibernate实现员工增删改查

public class Department implements java.io.Serializable {
private Integer deptno;//部门号
private String dname;//部门名字
private Set employees = new HashSet(0);
//省略get,set方法
}

public class Employee implements java.io.Serializable {
private Integer empno;//雇员ID
private Department department;//部门
private String ename;//名字
private String job;//职位
private Date hiredate;//职日期
private Double sal;//薪水
private String pictureuri;//照片
}


//查询所有员工
Session se=HibernateSessionFactory.getSession();
String sql="from Employee";
List<Employee> empList=se.createQuery(sql).list();
for (Employee emp : empList) {
System.out.print(emp.getEname());
System.out.println(emp.getDepartment().getDname());
}
//或者以下
List<Employee> empList= se.createCriteria(Employee.class).createCriteria("department").list();
for (Employee emp : empList) {
System.out.print(emp.getEname());
System.out.println(emp.getDepartment().getDname());
}

//根据一个ID删除一名员工
Employee emp=(Employee) se.get(Employee.class, 202);
se.delete(emp);
se.beginTransaction().commit();

//新增一名员工 
//要记得在映射文件里写上自己建数据库时的自增序列(ORACLE数据库)
<id name="empno" type="java.lang.Integer">
<column name="EMPNO" precision="8" scale="0" />
<generator class="sequence">
<param name="sequence">seq_emp</param>
</generator>
</id>
Employee emp=new Employee();
emp.setEname("abcde");
se.save(emp);
se.beginTransaction().commit();


//根据用户所选条件动态组合查询
public List<Employee> findEmployee(Employee emp){
List<Employee> empList =null;
Criteria criteria=getSession().createCriteria(Employee.class);
if(emp!=null){
if(!emp.getEname().trim().equals("")){
criteria.add(Restrictions.like("ename", "%"+emp.getEname().trim()+"%"));
}
if(emp.getDepartment().getDeptno()>0){
criteria.add(Restrictions.eq("department.deptno", emp.getDepartment().getDeptno()));
}
if(emp.getHiredate()!=null){
criteria.add(Restrictions.like("hiredate", emp.getHiredate()));
}
if(emp.getMaxsal()>0&&emp.getMinsal()>0){
criteria.add(Restrictions.between("sal", emp.getMinsal(), emp.getMaxsal()));
}
criteria=criteria.createCriteria("department");
empList=criteria.list();
}
return empList;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值