走前人的路,充实自己(2)

发布于 2015-11-16 / Java / 0条评论 / 1,060浏览

通过java反射机制+JdbcTemplate实现保存对象
不多说了,直接上马

package com.denghb.duanzi.tools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by denghb on 15/11/16. */ @Repository public class JdbcTools { private static final Logger log = LoggerFactory.getLogger(JdbcTools.class); @Autowired private JdbcTemplate jdbcTemplate; /** * 插入一条数据 * @param object * @return */ public int insert(Object object){ //用来存放sql语句 StringBuffer sql = new StringBuffer(); //用来存放?号的语句 StringBuffer paramsSql = new StringBuffer(); //用来存放参数值 List<Object> params = new ArrayList<Object>(); //类名就是表名 String tableName = object.getClass().getSimpleName().toLowerCase(); sql.append("insert into " + tableName + " ("); //计数器 int count=0; try { //分析列 Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = field.getName(); if("serialVersionUID".equals(fieldName)){ continue; } //获取具体参数值 Method getter = getGetter(object.getClass(), fieldName); if(getter == null){ continue; } Object value = getter.invoke(object); if(value == null){ //如果参数值是null就直接跳过(不允许覆盖为null值,规范要求更新的每个字段都要有值,没有值就是空字符串) continue; } if(count!=0){ sql.append(","); } // 字段名就是列名 sql.append(fieldName); if(count!=0){ paramsSql.append(","); } paramsSql.append("?"); params.add(value); count++; } } catch (Exception e) { log.debug(e.getMessage(),e); } sql.append(") values ("); sql.append(paramsSql); sql.append(")"); log.debug("sql:"+sql.toString()); log.debug("param:"+ Arrays.toString(params.toArray())); return jdbcTemplate.update(sql.toString(), params.toArray()); } /** * 获取属性的getter方法 * @param clazz * @param fieldName * @return */ private static <T> Method getGetter(Class<T> clazz, String fieldName){ String getterName = "get" + StringTools.firstCharToUpperCase(fieldName); Method getter = null; try { getter = clazz.getMethod(getterName); } catch (Exception e) { log.debug(getterName + " doesn't exist!",e); } return getter; } }

测试

public static void main( String[] args )
    {
        ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        JdbcTools jdbc = app.getBean(JdbcTools.class);
        User u = new User();
        u.setUserName("张三");
        //u.setGender(false);
        jdbc.insert(u);
    }

so easy

有兴趣的童鞋,可以自定义一些注解来实现复杂的功能

注解版

评论
站长统计