`

SimpleJdbcTemplate 扩展

 
阅读更多

http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html

http://www.mkyong.com/spring/spring-named-parameters-examples-in-simplejdbctemplate/

 

 

 

package com.snailteam.team.model;

public interface Model {

}

 

 

 

package com.snailteam.team.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "tuser")
public class User implements Model {
	@Id
	public int id;
	@Column(name = "username")
	public String username;
	@Column(name = "password")
	public String password;
	@Column(name = "reg_date")
	public Date reg_date;
	@Column(name = "version")
	public Integer version;
	public String lastIp;
}

 

 

package com.snailteam.team.model;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.sql.DataSource;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public class SimpleJdbcTemplateExt extends SimpleJdbcTemplate {

	public SimpleJdbcTemplateExt(DataSource dataSource) {
		super(dataSource);
	}

	public int insert(Model model) throws IllegalArgumentException,
			IllegalAccessException, SQLException {
		String tableName = "";
		Map<String, Object> parameters = this.model2Parameters(model);
		if (model.getClass().isAnnotationPresent(Table.class)) {
			Table table = model.getClass().getAnnotation(Table.class);
			tableName = table.name();
		}
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		for (String key : parameters.keySet()) {
			sb.append("," + key);
		}
		sb.append(")");

		MapSqlParameterSource paramSource = new MapSqlParameterSource();
		paramSource.addValues(parameters);
		KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
		this.getNamedParameterJdbcOperations().update(
				"insert into " + tableName + sb.toString().replace("(,", "(")
						+ "values"
						+ sb.toString().replace(",", ",:").replace("(,", "("),
				paramSource, generatedKeyHolder);
		return generatedKeyHolder.getKey().intValue();
	}

	public Map<String, Object> model2Parameters(Model model)
			throws IllegalArgumentException, IllegalAccessException {
		Map<String, Object> parameters = new HashMap<String, Object>();
		for (Field f : model.getClass().getFields()) {
			f.setAccessible(true);
			if (f.isAnnotationPresent(Id.class)) {
				Object obj = f.get(model);
				if (obj != null)
					parameters.put("id", obj);
			} else if (f.isAnnotationPresent(Column.class)) {
				Column column = f.getAnnotation(Column.class);
				Object obj = f.get(model);
				if (obj != null)
					parameters.put(column.name(), obj);
			}

		}
		return parameters;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> T select(final Class<T> classz, String sql,
			Map<String, Object> parameters) throws InstantiationException,
			IllegalAccessException {
		return (T) this.queryForObject(sql, new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				try {
					T object = classz.newInstance();
					for (Field f : object.getClass().getFields()) {
						f.setAccessible(true);
						if (f.isAnnotationPresent(Id.class)) {
							f.set(object, rs.getObject("id"));
						} else if (f.isAnnotationPresent(Column.class)) {
							Column column = f.getAnnotation(Column.class);
							f.set(object, rs.getObject(column.name()));
						}
					}
					return object;
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}

		}, parameters);

	}

	public <T> T parameters2Model(Class<T> clazz, Map<String, Object> parameters)
			throws IllegalArgumentException, IllegalAccessException,
			InstantiationException {
		T model = clazz.newInstance();
		for (Field f : model.getClass().getFields()) {
			f.setAccessible(true);
			if (f.isAnnotationPresent(Id.class)) {
				f.set(model, parameters.get("id"));
			} else if (f.isAnnotationPresent(Column.class)) {
				Column column = f.getAnnotation(Column.class);
				f.set(model, parameters.get(column.name()));
			}

		}
		return model;
	}
}

 

 

package com.snailteam.team.dao;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.hibernate.id.UUIDHexGenerator;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.snailteam.team.model.SimpleJdbcTemplateExt;
import com.snailteam.team.model.User;

@ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext*.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceTest {

	@Resource
	DataSource dataSource;

	@Test
	public void testInsert() throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException, SQLException {
		User tUser = new User();
		tUser.username = "xiaofancn";
		tUser.password = "apsdf";
		tUser.version = 3L;
		tUser.id = 5;
		tUser.reg_date = new Date();
		SimpleJdbcTemplateExt simpleJdbcTemplateExt = new SimpleJdbcTemplateExt(
				dataSource);
		System.out.println(simpleJdbcTemplateExt.insert(tUser));
	}

	@Test
	public void testSelect() throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException, SQLException,
			InstantiationException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", 1);
		SimpleJdbcTemplateExt simpleJdbcTemplateExt = new SimpleJdbcTemplateExt(
				dataSource);
		User user = simpleJdbcTemplateExt.select(User.class,
				"select * from vuser where id=:id", params);
		System.out.println(user);
	}
}

 

 

再来一个工具累

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.springframework.jdbc.InvalidResultSetAccessException;
import org.springframework.jdbc.support.rowset.SqlRowSet;

public class JdbcUntil {

	public static <T> T parameters2Model(Class<T> clazz,
			Map<String, Object> parameters) {
		T model = null;
		try {
			model = clazz.newInstance();
		} catch (InstantiationException e1) {
			println(e1.getMessage());
		} catch (IllegalAccessException e1) {
			println(e1.getMessage());
		}
		Field[] fields = model.getClass().getFields();
		for (Field f : fields) {
			if (parameters.get(f.getName()) == null
					|| parameters.get(f.getName()).equals("null"))
				continue;
			f.setAccessible(true);
			try {
				f.set(model, parameters.get(f.getName()));
			} catch (IllegalArgumentException e) {
				println(e.getMessage());
			} catch (IllegalAccessException e) {
				println(e.getMessage());
			}
		}
		return model;
	}

	public static <T> T resultSet2Model(Class<T> clazz, ResultSet rs) {
		T model = null;
		try {
			model = clazz.newInstance();
		} catch (InstantiationException e) {
			println(e.getMessage());
		} catch (IllegalAccessException e) {
			println(e.getMessage());
		} finally {
			if (model == null)
				return model;
		}
		Field[] fields = model.getClass().getFields();
		for (Field f : fields) {
			f.setAccessible(true);
			try {
				f.set(model, rs.getObject(f.getName()));
			} catch (IllegalArgumentException e) {
				try {
					if (f.getType().equals(Integer.class)) {
						f.set(model,
								Integer.valueOf("" + rs.getObject(f.getName())));
					} else if (f.getType().equals(Long.class)) {
						f.set(model,
								Long.valueOf("" + rs.getObject(f.getName())));
					}
				} catch (Exception e2) {
					println("转换" + f.getName() + "错误");
				}
			} catch (IllegalAccessException e) {
				println(e.getMessage());
			} catch (SQLException e) {
				println(e.getMessage());
			}
		}
		return model;
	}

	public static <T> T sqlRowSet2Model(Class<T> clazz, SqlRowSet parameters) {
		T model = null;
		try {
			model = clazz.newInstance();
		} catch (InstantiationException e) {
			println(e.getMessage());
		} catch (IllegalAccessException e) {
			println(e.getMessage());
		} finally {
			if (model == null)
				return model;
		}
		Field[] fields = model.getClass().getFields();
		for (Field f : fields) {
			f.setAccessible(true);
			try {
				f.set(model, parameters.getObject(f.getName()));
			} catch (InvalidResultSetAccessException e) {
				println(e.getMessage());
			} catch (IllegalArgumentException e) {
				println(e.getMessage());
			} catch (IllegalAccessException e) {
				println(e.getMessage());
			}
		}
		return model;
	}

	public static Map<String, Object> model2Parameters(Object obj,
			boolean needNull) {
		Map<String, Object> paraMap = new HashMap<String, Object>();
		for (Field f : obj.getClass().getFields()) {
			try {
				if (!needNull && !(f.get(obj) == null))
					paraMap.put(f.getName(), f.get(obj));
				else
					paraMap.put(f.getName(), f.get(obj));
			} catch (IllegalArgumentException e) {
				println(e.getMessage());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return paraMap;
	}

	public static String rowsFetchIdString(List<Map<String, Object>> rows,
			String keyword) {
		Set<Object> filter = new HashSet<Object>();
		StringBuffer sb = new StringBuffer();
		for (Map<String, Object> row : rows) {
			if (row.get(keyword) == null || filter.contains(row.get(keyword)))
				continue;
			filter.add(row.get(keyword));
			sb.append(row.get(keyword) + ",");
		}
		sb.append("-9");
		return sb.toString();
	}

	public static void println(String info) {
		System.out.println(new Date() + "JdbcUntil -----" + "  " + info);
	}
}

 

分享到:
评论

相关推荐

    使用Spring的SimpleJdbcTemplate完成DAO操作

    我的使用Spring的SimpleJdbcTemplate完成DAO操作实例 博文链接:https://zmx.iteye.com/blog/373749

    Spring之SimpleJdbcTemplate的使用

    NULL 博文链接:https://1194867672-qq-com.iteye.com/blog/1291025

    Spring 通过连接mysql,通过JdbcTemplate和SimpleJdbcTemplate来操作数据库

    本代码总结了,spring通过JdbcTemplate和SimpleJdbcTemplate来操作数据库的各种方法。 本代码使用的maven project。

    Spring4.0从入门到精通springmvcjdbctemplatedemo

    spring4.0的jdbctemplate与springmvc全注解的整合登陆例子.里面已经包括需要的jar包.使用的是j2ee6如果没有请升级你的eclipse或myeclipse

    Spring mysql数据库的配置与链接

    SimpleJdbcTemplate Spring Mysql

    用java调用oracle存储过程

    通过实例详细介绍了用java调用oracle存储过程的方法和步骤,包括无返回值的存储过程、有返回值的存储过程(非列表)和返回列表的存储过程的编写、JAVA调用,是一个对存储过程调用的一个全面总结,对程序开发具体实际...

    Maven+spring3.0MVC注释方式开发的Web应用

    使用Maven+spring3.0MVC注释方式+SimpleJdbcTemplate开发的Web CRUD应用,没有将jar包上传,可以自己去下载

    Spring中文帮助文档

    2.2.3. 可扩展的XML编写 2.2.4. Annotation(注解)驱动配置 2.2.5. 在classpath中自动搜索组件 2.3. 面向切面编程(AOP) 2.3.1. 更加简单的AOP XML配置 2.3.2. 对@AspectJ 切面的支持 2.3.3. 对bean命名pointcut...

    Spring API

    2.2.3. 可扩展的XML编写 2.2.4. Annotation(注解)驱动配置 2.2.5. 在classpath中自动搜索组件 2.3. 面向切面编程(AOP) 2.3.1. 更加简单的AOP XML配置 2.3.2. 对@AspectJ 切面的支持 2.3.3. 对bean命名pointcut...

    Spring.3.x企业应用开发实战(完整版).part2

    11.5.2 SimpleJDBCTemplate 11.6 以OO方式访问数据库 11.6.1 使用MappingSqlQuery查询数据 11.6.2 使用SqlUpdate更新数据 11.6.3 使用StoredProcedure执行存储过程 11.6.4 SqlFunction类 11.7 小结 第12章 整合其他...

    Spring3.x企业应用开发实战(完整版) part1

    11.5.2 SimpleJDBCTemplate 11.6 以OO方式访问数据库 11.6.1 使用MappingSqlQuery查询数据 11.6.2 使用SqlUpdate更新数据 11.6.3 使用StoredProcedure执行存储过程 11.6.4 SqlFunction类 11.7 小结 第12章 整合其他...

    Spring 2.0 开发参考手册

    11.2.3. SimpleJdbcTemplate类 11.2.4. DataSource接口 11.2.5. SQLExceptionTranslator接口 11.2.6. 执行SQL语句 11.2.7. 执行查询 11.2.8. 更新数据库 11.3. 控制数据库连接 11.3.1. DataSourceUtils类 ...

    spring chm文档

    11.2.3. SimpleJdbcTemplate类 11.2.4. DataSource接口 11.2.5. SQLExceptionTranslator接口 11.2.6. 执行SQL语句 11.2.7. 执行查询 11.2.8. 更新数据库 11.3. 控制数据库连接 11.3.1. DataSourceUtils类 ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    11.2.3. SimpleJdbcTemplate类 11.2.4. DataSource接口 11.2.5. SQLExceptionTranslator接口 11.2.6. 执行SQL语句 11.2.7. 执行查询 11.2.8. 更新数据库 11.3. 控制数据库连接 11.3.1. DataSourceUtils类 11.3.2. ...

    SPRING API 2.0.CHM

    All Classes AbstractAdvisorAutoProxyCreator AbstractApplicationContext AbstractApplicationEventMulticaster AbstractAspectJAdvice AbstractAspectJAdvisorFactory AbstractAspectJAdvisorFactory....

Global site tag (gtag.js) - Google Analytics