使用原生jdbc 封装一个简易的Orm

本文介绍如何利用原生jdbc来封装一个简单的对象关系映射(ORM)框架。包括数据库配置类DbContextOption、配置Builder类DbContextOptionBuilder、数据库上下文接口IDbContext及其具体实现DbContext。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用原生jdbc 封装一个简易的Orm

数据库配置类 DbContextOption
package jdbc读取数据库;

/**
 * 数据库配置类
 * @author QH
 *
 */
public class DbContextOption {
	/**
	 * 连接字符串
	 */
	 String connectString;
	 /**
	  * 用户名
	  */
	 String userName;
	 /**
	  * 密码
	  */
	 String password;
}
数据库配置Builder类 DbContextOptionBuilder
package jdbc读取数据库;

/**
 * 创建数据库连接配置
 * @author QH
 *
 */
public class DbContextOptionBuilder {
	DbContextOption option;
	public  DbContextOptionBuilder() {
		option=new DbContextOption();
	}
	/**
	 * 连接字符串
	 * @param connectionString
	 * @return
	 */
	public DbContextOptionBuilder withConnectionString(String connectionString) {
		option.connectString = connectionString;
		return this;
	}
	/**
	 * 用户名
	 * @param userName
	 * @return
	 */
	public DbContextOptionBuilder withUserName(String userName) {
		option.userName = userName;
		return this;
	}
	/**
	 * 密码
	 * @param password
	 * @return
	 */
	public DbContextOptionBuilder withPassword(String password) {
		option.password = password;
		return this;
	}
	/**
	 * 创建
	 * @return
	 */
	public DbContextOption Build() {
		return this.option;
	}
}

数据库上下文接口 IDbContext
package jdbc读取数据库;

import java.sql.SQLException;
import java.util.List;

/**
 * 数据上下文接口,包含常用操作数据库的方法
 * @author QH
 *
 */
public interface IDbContext {
	/**
	 * 执行sql语句 
	 * @param sqlText sql脚本
	 * @param args    查询参数
	 * @return 受影响行数
	 */
	int executeSqlCommand(String sqlText, Object... args) throws SQLException;
	/**
	 * 执行sql查询
	 * @param <T>
	 * @param tClass  类型
	 * @param sqlText sql语句
	 * @param args    参数
	 * @return 列表
	 */
	<T> List<T> sqlRawQuery(Class<T> tClass, String sqlText, Object... args) throws SQLException;

	/**
	 * 查询并返回第一行第一列的结果
	 * @param sqlText sql脚本
	 * @param args    查询参数
	 * @return 结果
	 */
	Object executeScalar(String sqlText, Object... args) throws SQLException;
	/**
	 * 开启事务
	 */
	void beginTransAction() throws SQLException;
	/**
	 * 提交事务
	 */
	void commit() throws SQLException;
	/**
	 * 回滚事务
	 */
	void rollback() throws SQLException;
	/**
	 * 关闭连接,释放资源
	 */
	void close() throws SQLException;
}

数据库上下文实现类 DbContext
package jdbc读取数据库;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据上下文实现类
 * @author QH
 *
 */
public class DbContext implements IDbContext {

	Connection connection;

	public DbContext(DbContextOption option) throws SQLException {
		this.connection = DriverManager.getConnection(option.connectString, option.userName, option.password);
	}

	/**
	 * 执行sql语句,返回受影响行数
	 */
	@Override
	public int executeSqlCommand(String sqlText, Object... args) throws SQLException {
		PreparedStatement statement = null;
		try {
			statement = this.connection.prepareStatement(sqlText);
			addParamters(statement, args);
			int n = statement.executeUpdate();
			return n;
		} finally {
			closeStatement(statement,null);
		}
	}

	/**
	 * 执行sql查询返回一个泛型列表
	 */
	@Override
	public <T> List<T> sqlRawQuery(Class<T> tClass, String sqlText, Object... args) throws SQLException {
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			statement = this.connection.prepareStatement(sqlText);
			addParamters(statement, args);
			resultSet = statement.executeQuery();
			return resolveList(tClass, resultSet);
		} finally {
			closeStatement(statement,resultSet);
		}
	}



	/**
	 * 执行sql查询,返回第一行第一列的值
	 */
	@Override
	public Object executeScalar(String sqlText, Object... args) throws SQLException {
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		Object result = null;
		try {
			statement = this.connection.prepareStatement(sqlText);
			addParamters(statement, args);
			resultSet = statement.executeQuery();
			if (resultSet.next()) {
				result = resultSet.getObject(1);
			}
		} finally {
			closeStatement(statement, resultSet);
		}
		return result;
	}

	/**
	 * 开启事务
	 */
	@Override
	public void beginTransAction() throws SQLException {
		if (this.connection != null) {
			this.connection.setAutoCommit(false);
		}
	}

	/**
	 * 提交事务
	 */
	@Override
	public void commit() throws SQLException {
		this.connection.commit();

	}

	/**
	 * 撤销事务
	 */
	@Override
	public void rollback() throws SQLException {
		this.connection.rollback();
	}

	/**
	 * 关闭连接,释放资源
	 */
	@Override
	public void close() throws SQLException {
		this.connection.close();
	}

	/**
	 * 从ResultSet中解析数据
	 * 
	 * @param <T>
	 * @param tClass
	 * @param resultSet
	 * @return
	 * @throws SQLException
	 */
	private <T> List<T> resolveList(Class<T> tClass, ResultSet resultSet) throws SQLException {
		List<T> resultList = new ArrayList<T>();
		if (resultSet == null) {
			return resultList;
		}
		ResultSetMetaData metaData = resultSet.getMetaData();
		Field[] fields = tClass.getFields();
		while (resultSet.next()) {
			T instanceT;
			try {
				instanceT = tClass.newInstance();
				for (int i = 1; i <= metaData.getColumnCount(); i++) {
					String label = metaData.getColumnLabel(i);
					Object value = resultSet.getObject(i);
					String dbType = metaData.getColumnTypeName(i);
					Field field = findField(fields, label);
					if (field != null) {
						field.setAccessible(true);
						field.set(instanceT, value);
					}
				}
			} catch (InstantiationException | IllegalAccessException e1) {
				e1.printStackTrace();
				return resultList;
			}
			resultList.add(instanceT);
		}
		return resultList;
	}

	private Field findField(Field[] fields, String label) {
		for (Field field : fields) {
			String fieldName = field.getName();

			if (fieldName.equalsIgnoreCase(label)) {
				return field;
			}
		}
		return null;
	}

	private void closeStatement(PreparedStatement statement, ResultSet resultSet) throws SQLException {
		if (statement != null) {
			statement.close();
		}
		if (resultSet != null) {
			resultSet.close();
		}
	}
	/**
	 * 参数化sql查询
	 * 
	 * @param statement
	 * @param args
	 * @throws SQLException
	 */
	private void addParamters(PreparedStatement statement, Object... args) throws SQLException {
		if (args != null && args.length > 0) {
			statement.clearParameters();
			for (int i = 0; i < args.length; i++) {
				statement.setObject(i + 1, args[i]);
			}
		}
	}

}

代码调用

public static void main(String[] args) throws SQLException {
		//创建配置
		DbContextOption option = new DbContextOptionBuilder()
				.withConnectionString("jdbc:mysql://localhost:3306/javaproject")
				.withUserName("root")
				.withPassword("123qwe")
				.Build();
		IDbContext context = new DbContext(option);
		

		//开启事务
		context.beginTransAction();
		//添加数据
		String sqlText = "insert into rbac_User(Id,account,password,userName,enabled,isAdmin,CreateTime) "
				+ "values(?,?,?,?,?,?,?)";
		String id = UUID.randomUUID().toString();
		String account = "maliu";
		String password="123qwe";
		String userName="马六";
		boolean enabled =true;
		boolean isAdmin = false;
		Date createTime=new  Date(System.currentTimeMillis());
		context.executeSqlCommand(sqlText,id,account,password,userName,enabled,isAdmin,createTime);
		//提交事务
		context.commit();
		System.out.println("添加信息成功!");
		
		//读取列表
		List<UserInfo> userList = context.sqlRawQuery(UserInfo.class, "select * from rbac_user limit ?,? ", 1,3);
		for (UserInfo userInfo : userList) {
			System.out.println(userInfo);
		}
		
		//读取单个数据
		Object obj = context.executeScalar("select userName from rbac_user where id=?", id);
		System.out.println(obj);
		
		
		//关闭连接
		context.close();
		
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值