Home > Database > Mysql Tutorial > 采用封装及反射原理封装一个将对象装换为对数据库操作的工具类

采用封装及反射原理封装一个将对象装换为对数据库操作的工具类

WBOY
Release: 2016-06-07 15:55:53
Original
1109 people have browsed it

package project02_Order_management.dao;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet

package project02_Order_management.dao;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BaseDao {
	/**
	 * 查询所有数据方法
	 */
	public static List findAll(Object obj, Connection conn) throws Exception {
		// 获取要操作对象的类
		Class clazz = obj.getClass();
		// 获取传入实体的所有方法;
		Method[] methods = clazz.getDeclaredMethods();
		// 获取传入实体中的所有的属性
		Field[] fields = clazz.getDeclaredFields();
		// 建立结果集List接收对象
		List list = new ArrayList();
		// 创建查询的sql语句;
		String sql = "select * from  "
				+ obj.getClass().getSimpleName().toLowerCase();
		System.out.println(sql);
		// System.out.println(sql);
		// 预编译sql语句
		PreparedStatement preparedStatement = conn.prepareStatement(sql);
		ResultSet resultSet = preparedStatement.executeQuery();
		// 从结果集中循环取出放入结果集List
		while (resultSet.next()) {
			// 查询的结果的接受对象
			Object entity = clazz.newInstance();

			// 循环类中的属性,进行复制操作
			for (int i = 0; i < fields.length; i++) {
				// 获取属性名称
				String fieldName = fields[i].getName();
				// 获取result结果集中的每个结果字段的对象
				Object fieldObject = resultSet.getObject(i + 1);
				if (fieldObject == null) {
					fieldObject = "null";// 防止数据为null时引发空指针异常
				}
				for (int j = 0; j < methods.length; j++) {
					// 比对属性名加上set后与方法名是否一致,进行对应的属性用对应的方法进行复制操作
					if (("set" + fieldName).equalsIgnoreCase(methods[j]
							.getName())) {
						// 执行传入对象的指定的方法
						methods[j].invoke(entity,
								resultSet.getObject(fieldName));
					}
				}
			}
			list.add(entity);
		}
		return list;
	}

	/**
	 * 根据id查询数据
	 * 
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 */
	public static Object findById(Object obj, Integer id, Connection conn)
			throws SQLException, InstantiationException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		// 获取要操作对象的类
		Class clazz = obj.getClass();
		// 获取传入实体的所有方法;
		Method[] methods = clazz.getDeclaredMethods();
		// 获取传入实体中的所有的属性
		Field[] fields = clazz.getDeclaredFields();
		// 查询的结果的接受对象
		Object entity = null;
		// 创建查询的sql语句;
		String sql = "select * from " + clazz.getSimpleName().toLowerCase()
				+ " where id=?";
		PreparedStatement preparedStatement = conn.prepareStatement(sql);
		preparedStatement.setInt(1, id);
		ResultSet resultSet = preparedStatement.executeQuery();
		if (resultSet.next()) {
			// 根据获取的实体的类,创建实体
			entity = clazz.newInstance();

			// 循环类中的属性,进行复制操作
			for (int i = 0; i < fields.length; i++) {
				// 获取属性名称
				String fieldName = fields[i].getName();

				// 获取result结果集中的每个结果字段的对象
				Object fieldObject = resultSet.getObject(i + 1);
				if (fieldObject == null) {
					fieldObject = "null";// 防止数据为null时引发空指针异常
				}

				for (int j = 0; j < methods.length; j++) {
					// 比对属性名加上set后与方法名是否一致,进行对应的属性用对应的方法进行复制操作
					if (("set" + fieldName).equalsIgnoreCase(methods[j]
							.getName())) {
						// 执行传入对象的指定的方法
						methods[j].invoke(entity,
								resultSet.getObject(fieldName));
					}
				}
			}
		}
		return entity;
	}

	/**
	 * 分页数据查询
	 * 
	 * @param obj
	 *            传入目标对象
	 * @param conn
	 *            传入数据库连接
	 * @param startRow
	 *            传入开始的行数
	 * @param endRow
	 *            传入结束的行数
	 */
	public static List paging(Object obj, Connection conn, Integer startRow,
			Integer endRow) {
		
		
		return null;
	}

	/**
	 * 保存方法
	 */
	public static void save(Object obj, Connection conn)
			throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, SQLException {
		Class clazz = obj.getClass();
		Method[] methods = clazz.getDeclaredMethods();
		Field[] fields = clazz.getDeclaredFields();

		// 获取操作的表单名字,[这里类名必须和表名一致]
		String table = clazz.getSimpleName().toLowerCase();
		String fieldsName = "";
		for (int i = 0; i < fields.length; i++) {
			fieldsName = fieldsName + fields[i].getName() + ",";
		}
		fieldsName = fieldsName.substring(0, fieldsName.length() - 1);

		// 占位符的设置
		String placeholder = "";
		for (int j = 0; j < fields.length; j++) {
			// 拼接属性的get的方法名
			String str = "get" + fields[j].getName();
			for (int k = 0; k < methods.length; k++) {
				if (str.equalsIgnoreCase(methods[k].getName())) {
					placeholder = placeholder + "?" + ",";
				}
			}
		}
		placeholder = placeholder.substring(0, placeholder.length() - 1);

		// 拼接sql语句
		String sql = "insert into " + table + "(" + fieldsName + ")"
				+ " values " + "(" + placeholder + ")";
		System.out.println(sql);
		PreparedStatement pst = conn.prepareStatement(sql);
		int index = 1;
		for (int j = 0; j < fields.length; j++) {
			String str = "get" + fields[j].getName();
			// 循环方法名比对
			for (int k = 0; k < methods.length; k++) {
				// 如果当前的属性拼出的get方法名,与方法明集合中的有一样的执行
				if (str.equalsIgnoreCase(methods[k].getName())) {
					// 接收指定的方法执行后的数据
					Object p = methods[k].invoke(obj);
					// 为指定的占位符进行赋值
					pst.setObject(index++, p);
				}
			}
		}
		// 执行已经加载的sql语句
		pst.executeUpdate();
	}

	/**
	 * 更新数据
	 */
	public static void update(Object obj, Connection conn) throws Exception {
		// 修改
		Class clazz = obj.getClass();
		Method[] methods = clazz.getDeclaredMethods();
		Field[] fields = clazz.getDeclaredFields();
		/*
		 * 拼接Sql
		 */
		String table = clazz.getSimpleName().toLowerCase();
		String setField = "";
		int id = 1;
		for (int i = 0; i < fields.length; i++) {
			for (int j = 0; j < methods.length; j++) {
				String strGetField = "get" + fields[i].getName();
				if (strGetField.equalsIgnoreCase(methods[j].getName())) {
					/*
					 * 拼接sql语句中的set字段,并用占位符
					 */
					setField = setField + fields[i].getName() + "= ?,";
					// 获取id
					if ("getId".equalsIgnoreCase(methods[j].getName())) {
						id = Integer
								.parseInt(methods[j].invoke(obj).toString());
					}
				}
			}
		}
		setField = setField.substring(0, setField.length() - 1);
		String sql = "update " + table + " set " + setField + " where id= ?";
		System.out.println(sql);
		PreparedStatement pst = conn.prepareStatement(sql);

		int index = 1;
		for (int j = 0; j < fields.length; j++) {
			String str = "get" + fields[j].getName();
			// 循环方法名比对
			for (int k = 0; k < methods.length; k++) {
				// 如果当前的属性拼出的get方法名,与方法明集合中的有一样的执行
				if (str.equalsIgnoreCase(methods[k].getName())) {
					// 接收指定的方法执行后的数据
					Object p = methods[k].invoke(obj);
					// 为指定的占位符进行赋值
					pst.setObject(index++, p);
				}
			}
		}
		pst.setObject(index++, id);
		pst.execute();

	}

	/**
	 * 根据id删除数据
	 * 
	 * @throws SQLException
	 */
	public static void delById(Object obj, Integer id, Connection conn)
			throws SQLException {
		System.out.println("=============");
		Class clazz = obj.getClass();
		String table = clazz.getSimpleName().toLowerCase();
		String sql = "delete from " + table + " where id=?";
		System.out.println(sql);
		PreparedStatement preparedStatement = conn.prepareStatement(sql);
		preparedStatement.setInt(1, id);
		preparedStatement.execute();
	}

}
Copy after login

注:类名必须与表名一致,不区分大小写;

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template