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

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

Jun 07, 2016 pm 03:55 PM
principle reflection object encapsulation tool operate database use

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

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

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Top 10 digital currency exchange app recommendations, top ten virtual currency exchanges in the currency circle Top 10 digital currency exchange app recommendations, top ten virtual currency exchanges in the currency circle Apr 22, 2025 pm 03:03 PM

Recommended apps on top ten digital currency exchanges: 1. OKX, 2. Binance, 3. gate.io, 4. Huobi, 5. Coinbase, 6. KuCoin, 7. Kraken, 8. Bitfinex, 9. Bybit, 10. Bitstamp, these apps provide real-time market trends, technical analysis and price reminders to help users monitor market dynamics in real time and make informed investment decisions.

Reliable and easy-to-use virtual currency exchange app recommendations The latest ranking of the top ten exchanges in the currency circle Reliable and easy-to-use virtual currency exchange app recommendations The latest ranking of the top ten exchanges in the currency circle Apr 22, 2025 pm 01:21 PM

The reliable and easy-to-use virtual currency exchange apps are: 1. Binance, 2. OKX, 3. Gate.io, 4. Coinbase, 5. Kraken, 6. Huobi Global, 7. Bitfinex, 8. KuCoin, 9. Bittrex, 10. Poloniex. These platforms were selected as the best for their transaction volume, user experience and security, and all offer registration, verification, deposit, withdrawal and transaction operations.

Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Apr 22, 2025 pm 03:00 PM

The top ten digital virtual currency apps are: 1. OKX, 2. Binance, 3. gate.io, 4. Coinbase, 5. Kraken, 6. Huobi, 7. KuCoin, 8. Bitfinex, 9. Bitstamp, 10. Poloniex. These exchanges are selected based on factors such as transaction volume, user experience and security, and all provide a variety of digital currency trading services and an efficient trading experience.

Meme Coin Exchange Ranking Meme Coin Main Exchange Top 10 Spots Meme Coin Exchange Ranking Meme Coin Main Exchange Top 10 Spots Apr 22, 2025 am 09:57 AM

The most suitable platforms for trading Meme coins include: 1. Binance, the world's largest, with high liquidity and low handling fees; 2. OkX, an efficient trading engine, supporting a variety of Meme coins; 3. XBIT, decentralized, supporting cross-chain trading; 4. Redim (Solana DEX), low cost, combined with Serum order book; 5. PancakeSwap (BSC DEX), low transaction fees and fast speed; 6. Orca (Solana DEX), user experience optimization; 7. Coinbase, high security, suitable for beginners; 8. Huobi, well-known in Asia, rich trading pairs; 9. DEXRabbit, intelligent

What are the digital currency trading platforms in 2025? The latest rankings of the top ten digital currency apps What are the digital currency trading platforms in 2025? The latest rankings of the top ten digital currency apps Apr 22, 2025 pm 03:09 PM

Recommended apps for the top ten virtual currency viewing platforms: 1. OKX, 2. Binance, 3. Gate.io, 4. Huobi, 5. Coinbase, 6. Kraken, 7. Bitfinex, 8. KuCoin, 9. Bybit, 10. Bitstamp, these platforms provide real-time market trends, technical analysis tools and user-friendly interfaces to help investors make effective market analysis and trading decisions.

What are the digital currency trading apps suitable for beginners? Learn about the coin circle in one article What are the digital currency trading apps suitable for beginners? Learn about the coin circle in one article Apr 22, 2025 am 08:45 AM

When choosing a digital currency trading platform suitable for beginners, you need to consider security, ease of use, educational resources and cost transparency: 1. Priority is given to platforms that provide cold storage, two-factor verification and asset insurance; 2. Apps with a simple interface and clear operation are more suitable for beginners; 3. The platform should provide learning tools such as tutorials and market analysis; 4. Pay attention to hidden costs such as transaction fees and cash withdrawal fees.

What are the free market viewing software websites? Ranking of the top ten free market viewing software in the currency circle What are the free market viewing software websites? Ranking of the top ten free market viewing software in the currency circle Apr 22, 2025 am 10:57 AM

The top three top ten free market viewing software in the currency circle are OKX, Binance and gate.io. 1. OKX provides a simple interface and real-time data, supporting a variety of charts and market analysis. 2. Binance has powerful functions, accurate data, and is suitable for all kinds of traders. 3. gate.io is known for its stability and comprehensiveness, and is suitable for long-term and short-term investors.

See all articles