[英]How to retrieve data from master list in Java
I have 10-12 tables, where my master data is there and I have to load them by using findAll()
facility of hibernate. 我有10到12个表,我的主数据在那里,我必须使用hibernate的
findAll()
工具加载它们。
So for all these 10-12 table I would required to write the same kind of method like this 因此,对于所有这些10-12表,我都需要编写类似这种方法
public List<XYZType> getAllXYZType() {
return XYZRepository.findAll();
}
So this kind of code will be repeated for 10-12 times for different entities. 因此,对于不同的实体,此类代码将重复10-12次。 Is there any way so that I can make it generic ?
有什么办法可以使它通用吗?
public <T> List<T> getAll(final Class<T> type) {
Session session = sessionFactory.getCurrentSession();
Criteria crit = session.createCriteria(type);
return crit.list();
}
in order to use it just pass the desired class to the function and it will return the list. 为了使用它,只需将所需的类传递给函数,它将返回列表。
In that case you need to make it generic, I think the Abstract Factory Pattern is what you are looking for. 在那种情况下,您需要使其通用,我认为您正在寻找“ 抽象工厂模式 ”。
Your code should be like this: 您的代码应如下所示:
public interface GenericDAO < T, ID extends Serializable > {
T findById(ID id);
List < T > findAll();
}
Take a look at DAO Factory patterns with Hibernate for further information. 查看Hibernate的DAO Factory模式以获取更多信息。
public static <T> List<T> getLst(final Class<T> beanClass) {
List<T> lst = new ArrayList<T>();
Session sess = MyUtils.getSessionFactory().openSession();
try {
Criteria cr= sess.createCriteria(beanClass);
lst = cr.list();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
sess.close();
}
return lst;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.