1 |
torben |
599 |
package dk.thoerup.hibertest1;
|
2 |
|
|
|
3 |
|
|
import java.util.List;
|
4 |
|
|
|
5 |
|
|
import org.hibernate.Criteria;
|
6 |
|
|
import org.hibernate.Session;
|
7 |
|
|
import org.hibernate.Transaction;
|
8 |
|
|
import org.hibernate.criterion.MatchMode;
|
9 |
|
|
import org.hibernate.criterion.Restrictions;
|
10 |
|
|
|
11 |
|
|
public class EmployeeDAO {
|
12 |
|
|
|
13 |
|
|
|
14 |
|
|
@SuppressWarnings("unchecked")
|
15 |
|
|
public List<Employee> getAll() {
|
16 |
|
|
Session session = HibernateUtil.getSessionFactory().openSession();
|
17 |
|
|
Transaction tx = session.beginTransaction(); // Dummy Transcaction
|
18 |
|
|
|
19 |
|
|
Criteria c = session.createCriteria(Employee.class);
|
20 |
|
|
java.util.List<Employee> list = c.list();
|
21 |
|
|
tx.rollback(); //since no changes was made, just as well rollback
|
22 |
|
|
session.close();
|
23 |
|
|
|
24 |
|
|
return list;
|
25 |
|
|
}
|
26 |
|
|
|
27 |
|
|
public void saveEmployee(Employee emp) {
|
28 |
|
|
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
|
29 |
|
|
|
30 |
|
|
Transaction tx = session.beginTransaction();
|
31 |
|
|
//session.save(emp); persist could be used here
|
32 |
|
|
session.persist(emp);
|
33 |
|
|
tx.commit();
|
34 |
|
|
|
35 |
|
|
//don't close if we're using getCurrentSession
|
36 |
|
|
//session.close();
|
37 |
|
|
}
|
38 |
|
|
public void updateEmployee(Employee emp) {
|
39 |
|
|
Session session = HibernateUtil.getSessionFactory().openSession();
|
40 |
|
|
|
41 |
|
|
Transaction tx = session.beginTransaction();
|
42 |
|
|
session.update(emp);
|
43 |
|
|
tx.commit();
|
44 |
|
|
session.close();
|
45 |
|
|
|
46 |
|
|
}
|
47 |
|
|
|
48 |
|
|
@SuppressWarnings("unchecked")
|
49 |
|
|
public List<Employee> getEmployeesByName(String name) {
|
50 |
|
|
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
|
51 |
|
|
|
52 |
|
|
Transaction tx = session.beginTransaction();
|
53 |
|
|
Criteria c = session.createCriteria(Employee.class);
|
54 |
|
|
c.add( Restrictions.ilike("name", name, MatchMode.ANYWHERE) );
|
55 |
|
|
List<Employee> emps = c.list();
|
56 |
|
|
|
57 |
|
|
tx.rollback();
|
58 |
|
|
return emps;
|
59 |
|
|
}
|
60 |
|
|
|
61 |
|
|
public Employee getEmployeeById(int id) {
|
62 |
|
|
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
|
63 |
|
|
|
64 |
|
|
Transaction tx = session.beginTransaction();
|
65 |
|
|
Criteria c = session.createCriteria(Employee.class);
|
66 |
|
|
c.add( Restrictions.eq("id", id));
|
67 |
|
|
Employee emp = (Employee) c.uniqueResult();
|
68 |
|
|
|
69 |
|
|
tx.rollback();
|
70 |
|
|
return emp;
|
71 |
|
|
}
|
72 |
|
|
|
73 |
|
|
public void deleteEmployee(Employee emp) {
|
74 |
|
|
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
|
75 |
|
|
|
76 |
|
|
Transaction tx = session.beginTransaction();
|
77 |
|
|
session.delete(emp);
|
78 |
|
|
tx.commit();
|
79 |
|
|
}
|
80 |
|
|
}
|