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

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();
	}

}

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

Statement
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
How Do I Drop or Modify an Existing View in MySQL?How Do I Drop or Modify an Existing View in MySQL?May 16, 2025 am 12:11 AM

TodropaviewinMySQL,use"DROPVIEWIFEXISTSview_name;"andtomodifyaview,use"CREATEORREPLACEVIEWview_nameASSELECT...".Whendroppingaview,considerdependenciesanduse"SHOWCREATEVIEWview_name;"tounderstanditsstructure.Whenmodifying

MySQL Views: Which design patterns can I use with it?MySQL Views: Which design patterns can I use with it?May 16, 2025 am 12:10 AM

MySQLViewscaneffectivelyutilizedesignpatternslikeAdapter,Decorator,Factory,andObserver.1)AdapterPatternadaptsdatafromdifferenttablesintoaunifiedview.2)DecoratorPatternenhancesdatawithcalculatedfields.3)FactoryPatterncreatesviewsthatproducedifferentda

What Are the Advantages of Using Views in MySQL?What Are the Advantages of Using Views in MySQL?May 16, 2025 am 12:09 AM

ViewsinMySQLarebeneficialforsimplifyingcomplexqueries,enhancingsecurity,ensuringdataconsistency,andoptimizingperformance.1)Theysimplifycomplexqueriesbyencapsulatingthemintoreusableviews.2)Viewsenhancesecuritybycontrollingdataaccess.3)Theyensuredataco

How Can I Create a Simple View in MySQL?How Can I Create a Simple View in MySQL?May 16, 2025 am 12:08 AM

TocreateasimpleviewinMySQL,usetheCREATEVIEWstatement.1)DefinetheviewwithCREATEVIEWview_nameAS.2)SpecifytheSELECTstatementtoretrievedesireddata.3)Usetheviewlikeatableforqueries.Viewssimplifydataaccessandenhancesecurity,butconsiderperformance,updatabil

MySQL Create User Statement: Examples and Common ErrorsMySQL Create User Statement: Examples and Common ErrorsMay 16, 2025 am 12:04 AM

TocreateusersinMySQL,usetheCREATEUSERstatement.1)Foralocaluser:CREATEUSER'localuser'@'localhost'IDENTIFIEDBY'securepassword';2)Foraremoteuser:CREATEUSER'remoteuser'@'%'IDENTIFIEDBY'strongpassword';3)Forauserwithaspecifichost:CREATEUSER'specificuser'@

What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!