1 24 package org.riotfamily.riot.hibernate.support; 25 26 import java.sql.SQLException ; 27 import java.util.Iterator ; 28 import java.util.List ; 29 30 import org.hibernate.HibernateException; 31 import org.hibernate.Query; 32 import org.hibernate.Session; 33 import org.springframework.beans.factory.InitializingBean; 34 import org.springframework.orm.hibernate3.HibernateCallback; 35 import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 36 37 public class SetupBean extends HibernateDaoSupport implements InitializingBean { 38 39 private List objects; 40 41 private String condition; 42 43 public void setObjects(List objects) { 44 this.objects = objects; 45 } 46 47 public void setCondition(String condition) { 48 this.condition = condition; 49 } 50 51 protected void initDao() throws Exception { 52 if (setupRequired()) { 53 Iterator it = objects.iterator(); 54 while (it.hasNext()) { 55 Object object = it.next(); 56 getHibernateTemplate().save(object); 57 } 58 } 59 } 60 61 protected boolean setupRequired() { 62 if (condition == null) { 63 return true; 64 } 65 Object test = getHibernateTemplate().execute(new HibernateCallback() { 66 public Object doInHibernate(Session session) 67 throws HibernateException, SQLException { 68 69 Query query = session.createQuery(condition); 70 query.setMaxResults(1); 71 return query.uniqueResult(); 72 }; 73 }); 74 if (test instanceof Number ) { 75 return ((Number ) test).intValue() == 0; 76 } 77 if (test instanceof Boolean ) { 78 return ((Boolean ) test).booleanValue(); 79 } 80 return test == null; 81 } 82 83 } 84 | Popular Tags |