I believe that everyone is using hibernate (I am using 3.6 here, because I prefer spring, but the hibernate4.x series are a lot of duplicates with spring later, and spring also thinks that, hibernate4.x is a very well-developed framework. spring3.x has discarded Many hibernate support classes since then, so I will not upgrade hibernate, during the configuration of the hibernate ing file, if there is one-to-many (or many-to-many) attributes, hintify provides an optimization mechanism, the lazy attribute, but the problem is, the configuration file is a one-time configuration. If some parts of my project require delayed loading, some parts do not require delayed loading. In this way, you must force lazy = false, in this way, the optimization mechanism will lose its meaning.
After a period of experience, I finally got along with a set of feasible solutions:
All the lazy properties in the project are set to true by default and are not set to false. A commonservice is added to the project, which provides two methods: query a single object and query list:
@Overridepublic Object findById(Class<?> Objclass, Class<?> idClass,Object id,String[] fields) {Object o = dao.findById(Objclass, (Serializable) idClass.cast(id));if(fields!=null){for(String field:fields){String targetMethod = "get"+upperFirstWord(field);Method[] methods = Objclass.getDeclaredMethods();for (Method m : methods) {if(m.getName().equals(targetMethod)){try {Hibernate.initialize(m.invoke(o));break;} catch (Exception e) {e.printStackTrace();}}}}}return o;}
ObjclassClass of the object to be queriedIdclassId field typeIDID valueFieldsFields to be initialized
public List<?> find(Class<?> entityClazz, QueryParameterSetter paraSetter, Sorter sorter, Page page,String[] fields) {DetachedCriteria dc = DetachedCriteria.forClass(entityClazz);if (paraSetter != null)paraSetter.setParameters(dc);if (sorter != null && sorter.getOrder() != null)dc.addOrder(sorter.getOrder());List<?> l = findPageListByCriteria(dc, page.getPageSize(), page.getRecordStartIndex());lazyInitialize(entityClazz,l,fields);return l;}private void lazyInitialize(Class<?> entityClazz,List<?> l ,String[] fields){if(fields!=null){for(String field:fields){String targetMethod = "get"+upperFirstWord(field);Method[] methods = entityClazz.getDeclaredMethods();for (Method m : methods) {if(m.getName().equals(targetMethod)){try {for(Object o:l){Hibernate.initialize(m.invoke(o));}} catch (Exception e) {e.printStackTrace();}}}}}}
EntityclazzEntity typeParasetterParameter Setting InterfaceSorterSorting rulesPagePaging object
FieldsFields to be initialized
In this case, you only need to use these two methods to load associated object data in the project, and you can specify attributes without loading them all, the performance has been greatly improved.
This is just a piece of code. I believe most programmers can understand it. As for those programmers who cannot understand it, let's figure it out.