Java Code Examples for org.apache.commons.beanutils.converters.SqlDateConverter

The following examples show how to use org.apache.commons.beanutils.converters.SqlDateConverter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-boot   Source File: MyBeanUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * map to bean
 * 转换过程中,由于属性的类型不同,需要分别转换。
 * java 反射机制,转换过程中属性的类型默认都是 String 类型,否则会抛出异常,而 BeanUtils 项目,做了大量转换工作,比 java 反射机制好用
 * BeanUtils 的 populate 方法,对 Date 属性转换,支持不好,需要自己编写转换器
 *
 * @param map  待转换的 map
 * @param bean 满足 bean 格式,且需要有无参的构造方法; bean 属性的名字应该和 map 的 key 相同
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static void mapToBean(Map<String, Object> map, Object bean) throws IllegalAccessException, InvocationTargetException {

    //注册几个转换器
    ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
    ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
    //注册一个类型转换器  解决 common-beanutils 为 Date 类型赋值问题
    ConvertUtils.register(new Converter() {
        //  @Override
        public Object convert(Class type, Object value) { // type : 目前所遇到的数据类型。  value :目前参数的值。
            // System.out.println(String.format("value = %s", value));

            if (value == null || value.equals("") || value.equals("null"))
                return null;
            Date date = null;
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = dateFormat.parse((String) value);
            } catch (Exception e) {

                e.printStackTrace();
            }

            return date;
        }

    }, Date.class);

    BeanUtils.populate(bean, map);
}
 
Example 2
/**
 * Sets the transactionCycleStartDate attribute.
 * 
 * @param transactionCycleStartDate The transactionCycleStartDate to set.
 */
public void setTransactionCycleStartDate(String transactionCycleStartDate) {
    if (StringUtils.isNotBlank(transactionCycleStartDate)) {
        this.transactionCycleStartDate = (Date) (new SqlDateConverter()).convert(Date.class, transactionCycleStartDate);
    }
}
 
Example 3
/**
 * Sets the transactionCycleEndDate attribute.
 * 
 * @param transactionCycleEndDate The transactionCycleEndDate to set.
 */
public void setTransactionCycleEndDate(String transactionCycleEndDate) {
    if (StringUtils.isNotBlank(transactionCycleEndDate)) {
        this.transactionCycleEndDate = (Date) (new SqlDateConverter()).convert(Date.class, transactionCycleEndDate);
    }
}