public class GenericDao <T, PK extends Serializable> {
private final Class<T> type;
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
public GenericDao(final Class<T> type) {
this.type = type;
}
public PK save(final T o) {
return (PK) sessionFactory.getCurrentSession().save(o);
}
// ... get,delete, etc
应用上下文 bean:
<bean id="fooDao" class="com.mycompany.dao.GenericDao">
<constructor-arg>
<value>com.mycompany.Foo</value>
</constructor-arg>
</bean>
并且在服务层中像这样调用:
@Autowired
private GenericDao<Foo, Integer> fooDao;
...
public doStuffIncludingSave(Foo foo)
fooDao.save(foo);
最佳答案
这是一个很好的起点 Generic DAO article它来自 2006 年,但其中包含一些很好的信息。为了更新 Spring、hibernate 和注释的通用 DAO,这就是我所做的。还有这个newer article也很有用。
所有标识符都是通用接口(interface),以确保该类具有 I getId()
和 setId(I id)
创建通用 DAO 接口(interface)
public interface GenericDao<T extends Identifier<I>, I extends Serializable> {
public T find(I id);
public void delete(T obj);
public void saveOrUpdate(T obj);
}
创建您的 GenericDAO 实现
public abstract class GenericDaoImpl<T extends Identifier<I>, I extends Serializable> implements GenericDao<T, I>{
private Class<T> type;
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected SessionFactory getSessionFactory() {
if (sessionFactory == null)
throw new IllegalStateException("SessionFactory has not been set on DAO before usage");
return sessionFactory;
}
public Class<T> getType() {
return type;
}
public GenericDaoImpl() {
this.type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@Transactional(readOnly = true)
@Override
public T find(I id) {
return (T) getSessionFactory().getCurrentSession().get(getType(), id);
}
@Transactional
@Override
public void delete(T obj) {
getSessionFactory().getCurrentSession().delete(obj);
}
@Transactional
@Override
public void saveOrUpdate(T obj) {
getSessionFactory().getCurrentSession().saveOrUpdate(obj);
}
}
对象 DAO 接口(interface):
public interface SomeObjectDao extends GenericDao<SomeObject, Long>{
}
对象 DAO 实现
@Repository
public class SomeObjectDaoImpl extends GenericDaoImpl<SomeObject, Long> implements SomeObjectDao {
}
现在在任何需要它的类中,比如服务类,你可以通过添加你需要的对象类 dao 来实现 Autowiring
@Autowired
private SomeObjectDao someObjectDao;
关于java - 带有 Hibernate 和 Spring 的通用 DAO,是不是比这更好的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9297036/