欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernate实现员工增删改查 博客分类: JAVA常用框架 HibernateJavaOracleSQL 

程序员文章站 2024-02-25 22:27:15
...
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;
	}