我希望UserDao类扩展GenericDAO,在其中我将拥有所有CRUD方法。我已经阅读了IBM的文章:http://www.ibm.com/developerworks/java/library/j-genericdao/index.html,但是我无法实现它。有人可以根据我的自定义UserDao类向我展示示例。
@Transactional(value="myTransactionManager")
public class UserDao {
@Qualifier("mySessionFactory")
public SessionFactoryImpl sessionFactory;
public void setSessionFactory(SessionFactoryImpl sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<UserEntity> getAll() {
Query query = sessionFactory.getCurrentSession().createQuery(
"from UserEntity ");
List<UserEntity> userList = query.list();
return userList;
}
public void updaet(UserEntity userEntity) {
sessionFactory.getCurrentSession().update(userEntity);
}
public void delete(UserEntity userEntity) {
sessionFactory.getCurrentSession().delete(userEntity);
}
public void save(UserEntity userEntity) {
sessionFactory.getCurrentSession().save(userEntity);
}
}
我试图写这样的课
public class GenericDao{
@Qualifier("mySessionFactory")
public SessionFactoryImpl sessionFactory;
public void setSessionFactory(SessionFactoryImpl sessionFactory) {
this.sessionFactory = sessionFactory;
}
public <T> List<T> getAll(Class<T> t) {
Query query = sessionFactory.getCurrentSession().createQuery(
"from " + t.getName());
List<T> list = query.list();
return list;
}
public <T> void save(T t) {
sessionFactory.getCurrentSession().save(t);
}
public <T> void update(T t) {
sessionFactory.getCurrentSession().update(t);
}
public <T> void delete(T t) {
sessionFactory.getCurrentSession().delete(t);
}
}
但是当我尝试像这样用UserDao提取数据时:
public List<UserEntity> getAll() {
List<UserEntity> list = UserDao.findAll();
}
行
List<UserEntity> list = UserDao.findAll();
的Eclipse IDE提供错误:方法findAll()
对于UserDao类型的定义不足。 最佳答案
这是我的实现:
GenericDao:
@Repository
public class GenericDao<T extends DbObject> {
@Autowired
private SessionFactory sessionFactory;
private Class<T> getParameterizedClass() {
return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public T findById(final Serializable id) {
return (T) getCurrentSession().get(getParameterizedClass(), id.toString());
}
public void persist(final T object) {
getCurrentSession().persist(object);
}
public void saveOrUpdate(final T object) {
getCurrentSession().saveOrUpdate(object);
}
public void delete(final T object) {
getCurrentSession().delete(object);
}
public T merge(final T object) {
return (T) getCurrentSession().merge(object);
}
}
UserDao:
public class UserDao extends GenericDao<User> {
}
实体 :
@Entity
@Table(name = "...")
public class User extends DbObject {
}
关于java - 如何在Hibernate中实现泛型DAO类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36591846/