首先构建数据库表
插入2条数据
构建一个对应的Bean类,get/set/toString方法省略。。。
Customer
int idCard;
String nameStr;
String addressStr;
int phoneCard;
看操作数据库的方法
DAO
package com.godinsec;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DAO {
//获取链接数据库的方法
public Connection getConnection() throws Exception {
//准备链接数据库的配置信息
String user = "root";
String password = "root";
String url = "jdbc:mysql:///mydatabase";
String driverClass = "com.mysql.jdbc.Driver";
//加载驱动
Class.forName(driverClass);
//获取链接
Connection connection = DriverManager.getConnection(url, user, password);
//返回给函数调用者的connection
return connection;
}
//关闭资源
public void release(ResultSet resultSet,
PreparedStatement preparedStatement, Statement statement,
Connection connection) throws Exception {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
// (一)插入、更新、删除都可以包含在其中
public void update(String sql, Object... args) throws Exception {
// 准备好2个初始化接口
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// 获取链接和PrepareStatement接口对象
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
// 执行更新操作
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
release(null, preparedStatement, null, connection);
}
}
// 查询一条语句,返回对应的对象
public <T> T get(Class<T> clazz, String sql, Object... args)
throws Exception {
T entity = null;
// 准备好4个初始化接口
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 获取connection
connection = getConnection();
// 获取PrepareStatement
preparedStatement = connection.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
// 进行查询,得到ResultSet
resultSet = preparedStatement.executeQuery();
// 若ResultSet有记录,准备一个Map<String,Object>-->>键:是列别名 值:列值
Map<String, Object> values = new HashMap<String, Object>();
// 得到ResultSetMetaData对象
ResultSetMetaData rsmd = resultSet.getMetaData();
while (resultSet.next()) {
// 有ResultSetMetaData对象得到结果集有多少列
int columCount = rsmd.getColumnCount();
// 有ResultSetMetaData对象得到结果集得到每列的列名
for (int i = 0; i < columCount; i++) {
String columnLabel = rsmd.getColumnLabel(i + 1);
Object columnValue = resultSet.getObject(i + 1);
Object columnValue1 = resultSet.getObject(columnLabel);
System.out.println(columnLabel+"::"+columnValue+"::"+columnValue1);
// 填充Map对象
values.put(columnLabel, columnValue);
}
// 用反射创建Class对应的对象
entity = clazz.newInstance();
// 遍历Map对象,利用反射填充对象的属性值
for (Map.Entry<String, Object> entry : values.entrySet()) {
// 属性名为Map中的key,属性值为Map中的value
String propertyName = entry.getKey();
Object value = entry.getValue();
System.out.println(propertyName+"-----"+value);
ReflectionUtils.setFieldValue(entity, propertyName, value);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
release(resultSet, preparedStatement, null, connection);
}
return entity;
}
// 查询多条记录,返回对应的对象集合
public <T> List<T> getForList(Class<T> clazz, String sql, Object... args) {
List<T> list = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 获取链接
connection = getConnection();
// 获取PrepareStatement对象
preparedStatement = connection.prepareStatement(sql);
// 填占位符
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
// 获取结果集
resultSet = preparedStatement.executeQuery();
// 若ResultSet有记录,准备一个List<Map<String , Object>>----键:是列别名 值:列值
// 一条map就是一条记录
List<Map<String, Object>> values = new ArrayList<>();
// 得到ResultSetMetaData对象
ResultSetMetaData rsmd = resultSet.getMetaData();
Map<String, Object> map = null;
// 判断并且处理结果集
while (resultSet.next()) {
map = new HashMap<>();
// 将每条记录放到每条map里面
for (int i = 0; i < rsmd.getColumnCount(); i++) {
String columnLable = rsmd.getColumnLabel(i + 1);
Object value = resultSet.getObject(i + 1);
map.put(columnLable, value);
}
// 将所有的map记录,放到values--list容器中
values.add(map);
}
T bean = null;
if (values.size() > 0) {
// 遍历list集合中的每一条map记录
for (Map<String, Object> m : values) {
bean = clazz.newInstance();
// 遍历没一条map记录的键、值
for (Map.Entry<String, Object> entry : m.entrySet()) {
String propertyName = entry.getKey();
Object value = entry.getValue();
// 通过反射进行赋值
ReflectionUtils
.setFieldValue(bean, propertyName, value);
// 或者通过BeanUtils工具类进行赋值
// BeanUtils.setProperty(bean,propertyName,value);
}
list.add(bean);
}
}
} catch (Exception e) {
} finally {
}
return list;
}
//获取某个字段,得到结果集: 该结果集应该只有一行, 且只有一列
public <E> E getForValue(String sql, Object... args) throws Exception {
//声明数据库需要的接口
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 1. 得到结果集
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return (E) resultSet.getObject(1);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
release(resultSet, preparedStatement, null, connection);
}
return null;
}
}
看看测试类
DAOTest
package com.godinsec;
import java.sql.Connection;
import java.util.List;
import org.junit.Test;
public class DAOTest {
DAO dao = new DAO();
// 测试链接数据库
@Test
public void testGetConnection() throws Exception {
Connection connection = dao.getConnection();
System.out.println(connection);
}
// 测试添加、删除、修改操作
@Test
public void testUpdate() throws Exception {
String sql = "insert into stu(id,"
+ "name,address,phone)values(?,?,?,?)";
dao.update(sql, 4, "he", "nanjing", 189);
}
// 测试查询单条语句
@Test
public void testGet() throws Exception {
String sql = "select id idCard,name nameStr,address addressStr,phone phoneCard"
+ " from stu where id = ?";
Customer customer = dao.get(Customer.class, sql, 2);
System.out.println(customer);
}
// 测试查询多条语句
@Test
public void testGetForList() {
String sql = "select id idCard,name nameStr,address addressStr,phone phoneCard from stu";
List<Customer> customers = dao.getForList(Customer.class, sql);
System.out.println(customers);
}
// 测试某个字段值
@Test
public void testGetForValue() throws Exception {
String sql = "select name from stu where phone = ?";
String id = dao.getForValue(sql, 111);
System.out.println(id);
}
}
在看一个反射的工具类
ReflectionUtils
package com.godinsec;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* 反射的 Utils 函数集合
* 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数
* @author Administrator
*
*/
public class ReflectionUtils {
/**
* 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param clazz
* @param index
* @return
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz, int index){
Type genType = clazz.getGenericSuperclass();
if(!(genType instanceof ParameterizedType)){
return Object.class;
}
Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
if(index >= params.length || index < 0){
return Object.class;
}
if(!(params[index] instanceof Class)){
return Object.class;
}
return (Class) params[index];
}
/**
* 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param <T>
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static<T> Class<T> getSuperGenericType(Class clazz){
return getSuperClassGenricType(clazz, 0);
}
/**
* 循环向上转型, 获取对象的 DeclaredMethod
* @param object
* @param methodName
* @param parameterTypes
* @return
*/
public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){
for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
//superClass.getMethod(methodName, parameterTypes);
return superClass.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
//Method 不在当前类定义, 继续向上转型
}
//..
}
return null;
}
/**
* 使 filed 变为可访问
* @param field
*/
public static void makeAccessible(Field field){
if(!Modifier.isPublic(field.getModifiers())){
field.setAccessible(true);
}
}
/**
* 循环向上转型, 获取对象的 DeclaredField
* @param object
* @param filedName
* @return
*/
public static Field getDeclaredField(Object object, String filedName){
for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
return superClass.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
//Field 不在当前类定义, 继续向上转型
}
}
return null;
}
/**
* 直接调用对象方法, 而忽略修饰符(private, protected)
* @param object
* @param methodName
* @param parameterTypes
* @param parameters
* @return
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
Object [] parameters) throws InvocationTargetException{
Method method = getDeclaredMethod(object, methodName, parameterTypes);
if(method == null){
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
}
method.setAccessible(true);
try {
return method.invoke(object, parameters);
} catch(IllegalAccessException e) {
System.out.println("不可能抛出的异常");
}
return null;
}
/**
* 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
* @param object
* @param fieldName
* @param value
*/
public static void setFieldValue(Object object, String fieldName, Object value){
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
makeAccessible(field);
try {
field.set(object, value);
} catch (IllegalAccessException e) {
System.out.println("不可能抛出的异常");
}
}
/**
* 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
* @param object
* @param fieldName
* @return
*/
public static Object getFieldValue(Object object, String fieldName){
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
makeAccessible(field);
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
System.out.println("不可能抛出的异常");
}
return result;
}
}
先看testGet方法输出:
idCard::2::2
nameStr::bbb::bbb
addressStr::nanjing::nanjing
phoneCard::222::222
idCard-----2
phoneCard-----222
nameStr-----bbb
addressStr-----nanjing
Customer [idCard=2, nameStr=bbb, addressStr=nanjing, phoneCard=222]
然后看testGetForList
[Customer [idCard=1, nameStr=aaa, addressStr=beijing, phoneCard=111], Customer [idCard=2, nameStr=bbb, addressStr=nanjing, phoneCard=222]]
继而看testGetForValue输出
aaa
最后看插入数据库testUpdate