JdbcRowMapper-JDBC泛型查询对象封装
2016-05-19 16:17
513 查看
JdbcRowMapper-JDBC泛型查询对象封装
使用此JdbcRowMapper,将会带来全新的体验哦:此处需要结合2个注解来使用:
@Table(name = "user") @Column(name="last_name")
package com.sun4j.data.jdbc.util; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.persistence.Column; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.RowMapper; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; public class JdbcRowMapper<T> implements RowMapper<T>{ /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); /** The class we are mapping to */ private Class<T> 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<String, PropertyDescriptor> mappedFields; /** Set of bean properties we provide mapping for */ private Set<String> mappedProperties; /** * Create a new {@code BeanPropertyRowMapper} for bean-style configuration. * @see #setMappedClass * @see #setCheckFullyPopulated */ public JdbcRowMapper() { } /** * Create a new {@code BeanPropertyRowMapper}, accepting unpopulated * properties in the target bean. * <p>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 JdbcRowMapper(Class<T> mappedClass) { initialize(mappedClass); } /** * Create a new {@code 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 JdbcRowMapper(Class<T> mappedClass, boolean checkFullyPopulated) { initialize(mappedClass); this.checkFullyPopulated = checkFullyPopulated; } /** * Set the class that each row should be mapped to. */ public void setMappedClass(Class<T> mappedClass) { if (this.mappedClass == null) { initialize(mappedClass); } else { if (this.mappedClass != mappedClass) { throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to " + mappedClass + " since it is already providing mapping for " + this.mappedClass); } } } /** * Get the class that we are mapping to. */ public final Class<T> getMappedClass() { return this.mappedClass; } /** * Set whether we're strictly validating that all bean properties have been mapped * from corresponding database fields. * <p>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. * <p>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 this.primitivesDefaultedForNullValue; } /** * Initialize the mapping metadata for the given class. * @param mappedClass the mapped class */ protected void initialize(Class<T> mappedClass) { this.mappedClass = mappedClass; this.mappedFields = new HashMap<String, PropertyDescriptor>(); this.mappedProperties = new HashSet<String>(); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null) { String name=pd.getName(); try { Field field =mappedClass.getDeclaredField(pd.getName()); if (field!=null) { Column column=field.getAnnotation(Column.class); if (column!=null) { name=column.name(); } } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } this.mappedFields.put(lowerCaseName(name), pd); String underscoredName = underscoreName(name); if (!lowerCaseName(name).equals(underscoredName)) { this.mappedFields.put(underscoredName, pd); } this.mappedProperties.add(name); } } } /** * 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 original name * @return the converted name * @since 4.2 * @see #lowerCaseName */ protected String underscoreName(String name) { if (!StringUtils.hasLength(name)) { return ""; } StringBuilder result = new StringBuilder(); result.append(lowerCaseName(name.substring(0, 1))); for (int i = 1; i < name.length(); i++) { String s = name.substring(i, i + 1); String slc = lowerCaseName(s); if (!s.equals(slc)) { result.append("_").append(slc); } else { result.append(s); } } return result.toString(); } /** * Convert the given name to lower case. * By default, conversions will happen within the US locale. * @param name the original name * @return the converted name * @since 4.2 */ protected String lowerCaseName(String name) { return name.toLowerCase(Locale.US); } /** * Extract the values for all columns in the current row. * <p>Utilizes public setters and result set metadata. * @see java.sql.ResultSetMetaData */ @Override public T mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); T mappedObject = BeanUtils.instantiate(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null); for (int index = 1; index <= columnCount; index++) { String column = JdbcUtils.lookupColumnName(rsmd, index); String field = lowerCaseName(column.replaceAll(" ", "")); PropertyDescriptor pd = this.mappedFields.get(field); if (pd != null) { try { Object value = getColumnValue(rs, index, pd); if (rowNumber == 0 && logger.isDebugEnabled()) { logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type [" + ClassUtils.getQualifiedName(pd.getPropertyType()) + "]"); } try { bw.setPropertyValue(pd.getName(), value); } catch (TypeMismatchException ex) { if (value == null && this.primitivesDefaultedForNullValue) { if (logger.isDebugEnabled()) { logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '" + column + "' with null value when setting property '" + pd.getName() + "' of type [" + ClassUtils.getQualifiedName(pd.getPropertyType()) + "] on object: " + mappedObject, ex); } } else { throw ex; } } if (populatedProperties != null) { populatedProperties.add(pd.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex); } } else { // No PropertyDescriptor found if (rowNumber == 0 && logger.isDebugEnabled()) { logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'"); } } } 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.getName() + "]: " + this.mappedProperties); } return mappedObject; } /** * Initialize the given BeanWrapper to be used for row mapping. * To be called for each row. * <p>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. * <p>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 {@code BeanPropertyRowMapper} * (with the mapped class specified only once). * @param mappedClass the class that each row should be mapped to */ public static <T> JdbcRowMapper<T> newInstance(Class<T> mappedClass) { return new JdbcRowMapper<T>(mappedClass); } }
使用示例:
@Override public T load(Serializable id) { String sql = "SELECT * FROM " + getTableName() + " WHERE id=?"; return jdbcTemplate.query(sql, JdbcRowMapper.newInstance(entityClass()), id).get(0); } @Override public List<T> findAll(String sql, Object... args) { return jdbcTemplate.query(sql, JdbcRowMapper.newInstance(entityClass()), args); }
获取泛型类:
private Class<T> entityClass() { return entityInformation.getJavaType(); //此处可以使用正常的获取泛型类的方式 } **或者** private Class<T> entityClass; @SuppressWarnings("unchecked") public JdbcBaseDaoImpl() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); entityClass = (Class<T>) type.getActualTypeArguments()[0]; System.out.println("Dao实现类是:" + entityClass.getName()); }
获取表名:
private String getTableName() { String name = entityClass().getAnnotation(Table.class).name(); if (StringUtils.isNotBlank(name)) { return name; } else { return entityClass().getSimpleName(); } }
相关文章推荐
- jdbc中的Statement和PreparedStatement接口对象
- Python动态类型的学习---引用的理解
- jackson、Gson反序列化 泛型
- JAVA泛型—— 3fe8 转
- JAVA泛型详解——转
- 土人系列AS入门教程 -- 对象篇
- C#托管堆对象实例包含内容分析
- C#实现获取不同对象中名称相同属性的方法
- javascript asp教程第十一课--Application 对象
- 编写高质量代码改善C#程序――使用泛型集合代替非泛型集合(建议20)
- PowerShell中使用Out-String命令把对象转换成字符串输出的例子
- 简单学习C#中的泛型方法使用
- C#通过反射创建自定义泛型
- VBS教程:对象-正则表达式(RegExp)对象
- C#泛型用法实例分析
- C#检查指定对象是否存在于ArrayList集合中的方法
- sql2008启动代理未将对象应用到实例解决方案
- C#编程自学之类和对象
- C++中对象的常引用、动态建立和释放相关知识讲解
- C语言泛型编程实例教程