You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
webcrawler/web/src/main/java/web/service/BaseService.java

84 lines
2.6 KiB

package web.service;
import db.annotation.Model;
import db.config.HibernateConfig;
import db.model.AbstractModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.util.ClassUtils;
import java.io.Serializable;
import java.util.List;
/**
* Created by reborn on 2017/7/28.
*/
public abstract class BaseService{
protected static Logger log=LogManager.getLogger();
protected HibernateTemplate hibernateTemplate;
public final HibernateTemplate getHibernateTemplate() {
if(hibernateTemplate==null) {
hibernateTemplate=HibernateConfig.get(ClassUtils.getUserClass(this.getClass()).getAnnotation(Model.class).value());
}
return hibernateTemplate;
}
public <T extends AbstractModel> Serializable save(T command) throws DataAccessException {
return getHibernateTemplate().save(command);
}
public <T extends AbstractModel> void update(T command) throws DataAccessException{
getHibernateTemplate().update(command);
}
public final <T extends AbstractModel> T get(T command) throws DataAccessException {
T model = (T) getHibernateTemplate().get(command.getClass(), command.primaryKey());
if (model != null) {
return model.cast();
} else {
return null;
}
}
public <T extends AbstractModel> void delete(T command) throws DataAccessException{
T model=get(command);
if(model!=null){
getHibernateTemplate().delete(model);
}
}
public final List find(DetachedCriteria criteria, int firstResult,int maxResults) throws DataAccessException{
return getHibernateTemplate().findByCriteria(criteria,firstResult,maxResults<getMaxResults()?maxResults:getMaxResults());
}
public final List find(DetachedCriteria criteria) throws DataAccessException{
return getHibernateTemplate().findByCriteria(criteria);
}
/**
* 限制分页查询最大显示数
* @return
*/
protected int getMaxResults(){
return 100;
}
/**
* 根据查询条件统计记录数
* @param criteria
* @return
*/
public Long rowCount(DetachedCriteria criteria){
return getHibernateTemplate().executeWithNativeSession(session -> (Long) criteria.setProjection(Projections.rowCount()).getExecutableCriteria(session).uniqueResult());
}
}