home层
public List eventStatistics(EventLogDTO event,Page page){
String start_time = event.getStart_time();
String end_time = event.getEnd_time();
String event_msg = event.getEvent_msg();
long event_level = event.getEvent_level();
String event_state = event.getEvent_state();
String layernumber = event.getLayernumber();
String path = event.getPath();
StringBuffer sql = new StringBuffer();
sql.append("select e.*,m.module_name");
sql.append(" FROM event_log e");
sql.append(" join MODULE_INFO m on e.MODULE_ID = m.MODULE_ID");
sql.append(" where 1=1");
sql.append(" and e.EVENT_STATE = '1'");
sql.append(" and (e.MODULE_ID in");
sql.append(" (select cm.module_Id");
sql.append(" from Composition_ModuleInfo cm");
sql.append(" where cm.devCom_Id in");
sql.append(" (select dc.id");
sql.append(" from DeviceComposition dc");
sql.append(" where 1=1 ");
if(null!=layernumber&&!layernumber.isEmpty()&&layernumber.equals("1")){
sql.append("");
}
if(null!=path&&!path.isEmpty()){
sql.append(" and dc.path like '%").append(path).append("%'");
}
sql.append(" ))) ");
if(event_level>0){
sql.append(" AND e.event_level= ").append(event_level);
}
if(null!=start_time&&!start_time.isEmpty()){
sql.append(" and e.EVENT_DATE >= '").append(start_time).append("'");
}
if(null!=end_time&&!end_time.isEmpty()){
sql.append(" and e.EVENT_DATE <= '").append(end_time).append("'");
}
if(null!=event_msg&&!event_msg.isEmpty()){
sql.append(" and e.EVENT_MSG like '%").append(event_msg).append("%'");
}
if(null!=event_state&&!event_state.isEmpty()){
sql.append(" and e.EVENT_STATE = '").append(event_state).append("'");
}
sql.append(" order by m.module_id,e.EVENT_LEVEL desc, e.period desc");
Query query = sessionFactory.getCurrentSession().createSQLQuery(sql.toString());
if(null != page){
int total = sqlCount(sql.toString());
page.setTotalCount(total);
query.setMaxResults(page.getLimit());
query.setFirstResult(page.getStart());
}
query.setResultTransformer(new BeanTransformerAdapter(EventLogDTO.class));
return query.list();
}
通常sql语句存入实体类都要\"标注字段进行转义,这个
BeanTransformerAdapter类 可以帮将select * 的字段自动转入实体类的字段里面,提高开发效率~
下载地址:http://download.csdn.net/detail/qq_34117825/9636876
BeanTransformerAdapter源代码
package com.njbh.fault.util;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.StringUtils;
/**
* 重写spirng NameDJbcTemplate方法解决
* Hibernate sql查询数据库映射JavaBean大小写转换
* @author xj
*
* @param
*/
public class BeanTransformerAdapter implements ResultTransformer {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
/** The class we are mapping to */
private Class mappedClass;
/** Whether we're strictly validating */
private boolean checkFullyPopulated = false;
/** Whether we're defaulting primitives when mapping a null value */
private boolean primitivesDefaultedForNullValue = false;
/** Map of the fields we provide mapping for */
private Map mappedFields;
/** Set of bean properties we provide mapping for */
private Set mappedProperties;
/**
* Create a new BeanPropertyRowMapper for bean-style configuration.
* @see #setMappedClass
* @see #setCheckFullyPopulated
*/
public BeanTransformerAdapter() {
}
/**
* Create a new BeanPropertyRowMapper, accepting unpopulated properties
* in the target bean.
* Consider using the {@link #newInstance} factory method instead,
* which allows for specifying the mapped type once only.
* @param mappedClass the class that each row should be mapped to
*/
public BeanTransformerAdapter(Class mappedClass) {
initialize(mappedClass);
}
/**
* Create a new BeanPropertyRowMapper.
* @param mappedClass the class that each row should be mapped to
* @param checkFullyPopulated whether we're strictly validating that
* all bean properties have been mapped from corresponding database fields
*/
public BeanTransformerAdapter(Class mappedClass, boolean checkFullyPopulated) {
initialize(mappedClass);
this.checkFullyPopulated = checkFullyPopulated;
}
/**
* Set the class that each row should be mapped to.
*/
public void setMappedClass(Class mappedClass) {
if (this.mappedClass == null) {
initialize(mappedClass);
} else {
if (!this.mappedClass.equals(mappedClass)) {
throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to "
+ mappedClass + " since it is already providing mapping for " + this.mappedClass);
}
}
}
/**
* Initialize the mapping metadata for the given class.
* @param mappedClass the mapped class.
*/
protected void initialize(Class mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap();
this.mappedProperties = new HashSet();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null) {
this.mappedFields.put(pd.getName().toLowerCase(), pd);
String underscoredName = underscoreName(pd.getName());
if (!pd.getName().toLowerCase().equals(underscoredName)) {
this.mappedFields.put(underscoredName, pd);
}
this.mappedProperties.add(pd.getName());
}
}
}
/**
* Convert a name in camelCase to an underscored name in lower case.
* Any upper case letters are converted to lower case with a preceding underscore.
* @param name the string containing original name
* @return the converted name
*/
private String underscoreName(String name) {
if (!StringUtils.hasLength(name)) {
return "";
}
StringBuilder result = new StringBuilder();
result.append(name.substring(0, 1).toLowerCase());
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
String slc = s.toLowerCase();
if (!s.equals(slc)) {
result.append("_").append(slc);
} else {
result.append(s);
}
}
return result.toString();
}
/**
* Get the class that we are mapping to.
*/
public final Class getMappedClass() {
return this.mappedClass;
}
/**
* Set whether we're strictly validating that all bean properties have been
* mapped from corresponding database fields.
* Default is {@code false}, accepting unpopulated properties in the
* target bean.
*/
public void setCheckFullyPopulated(boolean checkFullyPopulated) {
this.checkFullyPopulated = checkFullyPopulated;
}
/**
* Return whether we're strictly validating that all bean properties have been
* mapped from corresponding database fields.
*/
public boolean isCheckFullyPopulated() {
return this.checkFullyPopulated;
}
/**
* Set whether we're defaulting Java primitives in the case of mapping a null value
* from corresponding database fields.
*
Default is {@code false}, throwing an exception when nulls are mapped to Java primitives.
*/
public void setPrimitivesDefaultedForNullValue(boolean primitivesDefaultedForNullValue) {
this.primitivesDefaultedForNullValue = primitivesDefaultedForNullValue;
}
/**
* Return whether we're defaulting Java primitives in the case of mapping a null value
* from corresponding database fields.
*/
public boolean isPrimitivesDefaultedForNullValue() {
return primitivesDefaultedForNullValue;
}
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
*
The default implementation is empty. Can be overridden in subclasses.
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
}
/**
* Retrieve a JDBC object value for the specified column.
*
The default implementation calls
* {@link JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)}.
* Subclasses may override this to check specific value types upfront,
* or to post-process values return from {@code getResultSetValue}.
* @param rs is the ResultSet holding the data
* @param index is the column index
* @param pd the bean property that each result object is expected to match
* (or {@code null} if none specified)
* @return the Object value
* @throws SQLException in case of extraction failure
* @see org.springframework.jdbc.support.JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)
*/
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
}
/**
* Static factory method to create a new BeanPropertyRowMapper
* (with the mapped class specified only once).
* @param mappedClass the class that each row should be mapped to
*/
public static BeanPropertyRowMapper newInstance(Class mappedClass) {
BeanPropertyRowMapper newInstance = new BeanPropertyRowMapper();
newInstance.setMappedClass(mappedClass);
return newInstance;
}
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
T mappedObject = BeanUtils.instantiate(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
Set populatedProperties = (isCheckFullyPopulated() ? new HashSet() : null);
for (int i = 0; i < aliases.length; i++) {
String column = aliases[i];
PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
if (pd != null) {
try {
Object value = tuple[i];
try {
bw.setPropertyValue(pd.getName(), value);
} catch (TypeMismatchException e) {
if (value == null && primitivesDefaultedForNullValue) {
logger.debug("Intercepted TypeMismatchException for column " + column + " and column '"
+ column + "' with value " + value + " when setting property '" + pd.getName() + "' of type " + pd.getPropertyType()
+ " on object: " + mappedObject);
} else {
throw e;
}
}
if (populatedProperties != null) {
populatedProperties.add(pd.getName());
}
} catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException("Unable to map column " + column
+ " to property " + pd.getName(), ex);
}
}
}
if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
+ "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
}
return mappedObject;
}
@Override
public List transformList(List list) {
return list;
}
}