1 /**************************************************************************
2 Copyright 2005 Webstersmalley
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 *************************************************************************/
16
17
18
19 package com.webstersmalley.picweb.online.db;
20
21 import java.util.Collection;
22 import java.util.Iterator;
23 import java.util.List;
24
25 import org.hibernate.HibernateException;
26 import org.springframework.dao.DataAccessException;
27 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
28
29 import com.webstersmalley.picweb.online.bus.Category;
30 import com.webstersmalley.picweb.online.bus.CategoryNotFoundException;
31 import com.webstersmalley.picweb.online.bus.Picture;
32
33 public class CategoryDaoHibernate extends HibernateDaoSupport implements
34 CategoryDao {
35
36 private PictureDao pictureDao;
37
38 public void setPictureDao(PictureDao pictureDao) {
39 this.pictureDao = pictureDao;
40 }
41
42 public Collection loadCategories() {
43 return getHibernateTemplate().loadAll(Category.class);
44 }
45
46 public Category getCategory(String name) {
47 try {
48 List list = getHibernateTemplate().find(
49 "from Category where name = ?", name);
50 if (list.size() == 0) {
51 throw new CategoryNotFoundException();
52 } else if (list.size() == 1) {
53 return (Category) list.get(0);
54 } else {
55 throw new RuntimeException("More than one rows returned");
56 }
57 } catch (HibernateException ex) {
58 throw convertHibernateAccessException(ex);
59 }
60 }
61
62 public void createAndStoreCategory(Category cat) {
63 for (Iterator it = cat.getPictures().iterator(); it.hasNext();) {
64 pictureDao.createAndStorePicture((Picture) it.next());
65 }
66 for (Iterator it = cat.getSubcategories().iterator(); it.hasNext();) {
67 createAndStoreCategory((Category) it.next());
68 }
69 getHibernateTemplate().saveOrUpdate(cat);
70 }
71
72 public Category getCategory(int id) {
73 return (Category) getHibernateTemplate().load(Category.class,
74 new Integer(id));
75 }
76
77 public Collection getRootCategories() {
78 return getHibernateTemplate().find("from Category");
79 }
80
81 }