日期:2014-05-18 浏览次数:20950 次
package com.util;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
public class BasicDao<T> {
private HibernateTemplate hibernateTemplate;
private Class entityClass;
public BasicDao(){
Type genType = getClass().getGenericSuperclass();
Type[] params=((ParameterizedType)genType).getActualTypeArguments();
entityClass = (Class)params[0];
}
public void setHibernateTemplate(HibernateTemplate h){
this.hibernateTemplate=h;
}
//添加
public void insert(T entity){
hibernateTemplate.save(entity);
}
//修改
public void update(T entity){
hibernateTemplate.update(entity);
}
//删除
public void delete(T entity){
hibernateTemplate.delete(entity);
}
//查询
public T get(Serializable id){
return (T)hibernateTemplate.get(entityClass, id);
}
//按条件查询
public List<T> find(String hql,Object param){
return (List<T>)hibernateTemplate.find(hql, param);
}
public HibernateTemplate getHibernateTemplate(){
return hibernateTemplate;
}
}
package com.user.dao;
import com.jdbc.bean.User;
import com.util.BasicDao;
public class UserDao extends BasicDao<User> {
}
public static void main(String[] arg0){
Test test = new Test();
UserDao userDao = new UserDao();
List results = userDao.find("from T_USER where USER_NAME LIKE ?", "%zhanghang%");
System.out.println("name password lastTime lastIp");
for(int i=0;i<results.size();i++){
System.out.println(((User)results.get(i)).getUserName()+" "+((User)results.get(i)).getPassword()+" "+((User)results.get(i)).getLastTime()+" "+((User)results.get(i)).getLastIp());
}
}
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="${driver}"
p:url="${url}"
p:username="${name}"
p:password="${password}"
/>
&l