日期:2014-05-20 浏览次数:20783 次
package com.lulu.ssh.dao; import java.sql.SQLException; import java.util.List; import javax.annotation.Resource; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Component; @Component("dao") public class DAO<T> { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public T get(Class clazz, int id) { return (T) hibernateTemplate.get(clazz, id); } public void save(T t) { hibernateTemplate.save(t); } public void delete(T t) { hibernateTemplate.delete(t); } public void update(T t) { hibernateTemplate.update(t); } public List<T> search(final Class<T> clazz, final int start, final int limit, final AddRestrictions addRestrictions) throws Exception { return hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(Session s) throws HibernateException, SQLException { Criteria c = s.createCriteria(clazz); if(limit != 0){ c.setFirstResult(start); c.setMaxResults(limit); } addRestrictions.addRestrictions(c); return c.list(); } }); } }
package com.lulu.ssh.dao; import org.hibernate.Criteria; public interface AddRestrictions { public void addRestrictions(Criteria c); }
package com.lulu.ssh.business; import java.util.List; import javax.annotation.Resource; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Component; import com.lulu.ssh.dao.AddRestrictions; import com.lulu.ssh.dao.DAO; import com.lulu.ssh.model.User; @Component("userBusiness") public class UserBusiness { private DAO<User> dao; public DAO<User> getDao() { return dao; } @Resource public void setDao(DAO<User> dao) { this.dao = dao; } public User getUser(int id) { return dao.get(User.class, id); } //这里可以分页,limit传0就不分页 public List<User> getUsers(final User condition, final int start, final int limit) throws Exception { return dao.search(User.class, start, limit, new AddRestrictions() { @Override public void addRestrictions(Criteria c) { //要什么条件这里按需求添加 c.add(Restrictions.like("descn", condition.getDescn(), MatchMode.ANYWHERE)); c.add(Restrictions.eq("name", condition.getName())); } }); } }