1 package org.springframework.samples.petclinic.hibernate;
2
3 import java.util.Collection;
4
5 import org.hibernate.SessionFactory;
6
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.dao.DataAccessException;
9 import org.springframework.samples.petclinic.Clinic;
10 import org.springframework.samples.petclinic.Owner;
11 import org.springframework.samples.petclinic.Pet;
12 import org.springframework.samples.petclinic.PetType;
13 import org.springframework.samples.petclinic.Vet;
14 import org.springframework.samples.petclinic.Visit;
15 import org.springframework.stereotype.Repository;
16 import org.springframework.transaction.annotation.Transactional;
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 @Repository
35 @Transactional
36 public class HibernateClinic implements Clinic {
37
38 private SessionFactory sessionFactory;
39
40 @Autowired
41 public HibernateClinic(SessionFactory sessionFactory) {
42 this.sessionFactory = sessionFactory;
43 }
44
45 @Transactional(readOnly = true)
46 @SuppressWarnings("unchecked")
47 public Collection<Vet> getVets() {
48 return sessionFactory.getCurrentSession().createQuery("from Vet vet order by vet.lastName, vet.firstName").list();
49 }
50
51 @Transactional(readOnly = true)
52 @SuppressWarnings("unchecked")
53 public Collection<PetType> getPetTypes() {
54 return sessionFactory.getCurrentSession().createQuery("from PetType type order by type.name").list();
55 }
56
57 @Transactional(readOnly = true)
58 @SuppressWarnings("unchecked")
59 public Collection<Owner> findOwners(String lastName) {
60 return sessionFactory.getCurrentSession().createQuery("from Owner owner where owner.lastName like :lastName")
61 .setString("lastName", lastName + "%").list();
62 }
63
64 @Transactional(readOnly = true)
65 public Owner loadOwner(int id) {
66 return (Owner) sessionFactory.getCurrentSession().load(Owner.class, id);
67 }
68
69 @Transactional(readOnly = true)
70 public Pet loadPet(int id) {
71 return (Pet) sessionFactory.getCurrentSession().load(Pet.class, id);
72 }
73
74 public void storeOwner(Owner owner) {
75
76
77
78
79
80
81
82 sessionFactory.getCurrentSession().merge(owner);
83 }
84
85 public void storePet(Pet pet) {
86 sessionFactory.getCurrentSession().merge(pet);
87 }
88
89 public void storeVisit(Visit visit) {
90 sessionFactory.getCurrentSession().merge(visit);
91 }
92
93 public void deletePet(int id) throws DataAccessException {
94 Pet pet = loadPet(id);
95 sessionFactory.getCurrentSession().delete(pet);
96 }
97
98 }