HibernateTemplate DAO
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class UserDAO extends HibernateDaoSupport


{
public void addUser(User user)

{
this.getHibernateTemplate().save(user);
}
public void updateUser(User entity)

{
this.getHibernateTemplate().save(entity);
}
public void deleteUser(User entity)

{
this.getHibernateTemplate().delete(entity);
}
public User getUser(int entityId)

{
return (User) this.getHibernateTemplate().get(User.class, entityId);
}
@SuppressWarnings("unchecked")
public List<User> findUsers()

{
return getHibernateTemplate().executeFind(new HibernateCallback()

{
@SuppressWarnings("unchecked")
public List<User> doInHibernate(Session session)
throws HibernateException, SQLException

{
StringBuffer sql = new StringBuffer(
"from User u where 1=1 ");
Query query = session.createQuery(sql.toString());
List<User> users = query.list();
return users;
}
});
}
public Long getUserNum()

{
return (Long) getHibernateTemplate().execute(new HibernateCallback()

{
public Long doInHibernate(Session session)
throws HibernateException, SQLException

{
Query query = session
.createQuery("SELECT COUNT(u.userId) FROM User u");
return (Long) query.uniqueResult();
}
});
}
public static void main(String[] a)

{
User user = new User();
user.setUserName("hwpokay");
user.setSex(0);
String configPath = "hvp/spring/hibernate/orm/beans.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
UserDAO userDAO = (UserDAO) ctx.getBean("userDAO");
System.out.println(userDAO.getUserNum());
}
}