ORM底层封装( JDBC \ DBUtils)

1:导入lib包


2:引入连接池配置文件


3:工具类

3.1: DataSourceUtils

/**
 * 加载properties配置文件 + oracle驱动
 */
public class DataSourceUtils{

	public static Properties properties = new Properties();
	private static DataSource dataSource;
	
	static {
		try {
			
			// 加载配置文件
			InputStream is = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("properties.properties");
			properties.load(is);
			
			// 加载oracle驱动
			Class.forName(properties.getProperty("driverClass"));
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/* 获取连接对象 */
	public static Connection getConnection() {

		String oracleUrl = properties.getProperty("oracleUrl");
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		try {

			return DriverManager.getConnection(oracleUrl, user, password);

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	/*获取c3p0数据源*/
	public static DataSource getC3P0DataSource() {
		
		if(dataSource==null){
			try
			{
				dataSource = new ComboPooledDataSource();
			}catch(Exception e){
				throw new RuntimeException(e + "\tclasspath下找不到  [c3p0-config.xml] 配置文件 ");
			}
		}
		
		return dataSource;
	}
	
}


 
3.2:DBUtils 

/**
 *	对DBUtils的sql操作简单封装 
 *		
 */
@SuppressWarnings({"rawtypes","unchecked"})
public class DBUtils {
	
	/**
	 * 	查询操作
	 * 	params	1: runner :QueryRunner操作对象      2: appEndSql: where条件sql语句        3: params:占位符参参数	 4: 对数据库字段一一对应的bean类
	 *  return  list包装:符合条件的对象
	 */
	
	public static List<Object> executionQuery(QueryRunner runner,String appEndSql,List params,Class clazz){
		
		List<Object> query = null;
		try {
			String sql = "SELECT * FROM "+clazz.getSimpleName()+" WHERE 1=1 " + appEndSql;
			System.out.println(sql);
			
			query = runner.query(sql,new BeanListHandler<>(clazz),params.toArray());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
		return query;
	}
	
	
	/**
	 * 	更新操作:增、删、改
	 * 	params	1:runner=QueryRunner操作对象      2: sql:sql语句        3: params:占位符参参数
	 *  return  更新的记录数
	 */
	public static int executionUpdate(QueryRunner runner,String sql,List params){
		
		Connection con = null;
		int updateNumb;
		try {
			//从数据库中获取连接对象
			con = runner.getDataSource().getConnection();
			
			con.setAutoCommit(false);//取消自动提交事务
			
			updateNumb = runner.update(sql,params.toArray());
			
			con.commit();//提交
		} catch (Exception e) {
			try {
				if(con!=null)
					con.rollback();			//回滚
				
			} catch (SQLException e1) {
				throw new RuntimeException(e1);
			}
			throw new RuntimeException(e);
		}
		
		return updateNumb;
	}
	
	
	/**
	 * 	查询操作
	 * 	params	1: con连接对象      2: appEndSql: where条件sql语句        3: params:占位符参参数	 4: 对数据库字段一一对应的bean类
	 *  return  list包装:符合条件的对象
	 */
	public static List<Object> executionQuery(Connection con,String appEndSql,List params,Class clazz){
		QueryRunner runner = new QueryRunner();
		
		List<Object> query = null;
		try {
			String sql = "SELECT * FROM "+clazz.getSimpleName()+" WHERE 1=1 " + appEndSql;
			System.out.println(sql);
			
			query = runner.query(con,sql,new BeanListHandler<>(clazz),params.toArray());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
		return query;
	}
	
	
	/**
	 * 	更新操作:增、删、改
	 * 	params	1: con连接对象      2: sql:sql语句        3: params:占位符参参数
	 *  return  更新的记录数
	 */
	public static int executionUpdate(Connection con,String sql,List params){
		QueryRunner runner = new QueryRunner();
		
		int updateNumb;
		try {
			
			con.setAutoCommit(false);//取消自动提交事务
			
			updateNumb = runner.update(con,sql,params.toArray());
			
			con.commit();//提交
		} catch (Exception e) {
			try {
				
				con.rollback();			//回滚
				
			} catch (SQLException e1) {
				throw new RuntimeException(e1);
			}
			throw new RuntimeException(e);
		}
		
		return updateNumb;
	}
}


3.3 JDBCUtils

/**
 * @author hubiao
 * JDBC工具类
 */
@SuppressWarnings({"rawtypes","unchecked"})
public class JDBCUtils {
	
	/** 设置日期格式*/
	public static String dateForma = "yyyy-MM-DD HH:mm:ss.SS"; 
	
	
	/**
	 * 	executeUpdate:执行:add、update、delete
	 * 	params
	 * 		con:Connection连接对象
	 * 		sql:操作数据库的sql语句
	 * 		params:参数对象
	 * 	return
	 * 		int 更新记录数
	 */
	public static int executionUpdate(Connection con,String sql,List<Object> params) {
		
		int update;
		
		try {
			con.setAutoCommit(false);
			
			PreparedStatement statement = con.prepareStatement(sql);
			
			for(int x = 1; x <=params.size() ;x ++){
				statement.setObject(x, params.get(x-1));
			}
			
			update = statement.executeUpdate();
			
			con.commit();
		} catch (Exception e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				throw new RuntimeException(e);
			}
			
			throw new RuntimeException(e);
		}
		
		return update;
	}
	/**
	 * 	executeQuery:执行:add、update、delete
	 * 	params
	 * 		con:Connection连接对象
	 * 		sql:操作数据库的sql语句
	 * 		params:参数对象
	 * 	return
	 * 		int 更新记录数
	 */
	
	public static List executionQuery(Connection con,String appEndSql,List<Object> params,Class clazz) {
		List arrayList = new ArrayList();
		
		ResultSet executeQuery = null;
		
		try {
			String sql = String.format("SELECT * FROM %s WHERE 1 = 1 %S",clazz.getSimpleName() ,appEndSql);
			System.out.println(sql);
			PreparedStatement statement = con.prepareStatement(sql);
			
			for(int x = 1; x <=params.size() ;x ++){
				statement.setObject(x, params.get(x-1));
			}
			
			executeQuery = statement.executeQuery();
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		try {
			
			while(executeQuery.next()){
				Object instance = clazz.newInstance();
				
				Field[] fields = clazz.getDeclaredFields();
				
				for(Field f : fields){
					String fieldName = f.getName();
					
					Method method = null;
					String methodName = null;
					try{
						//组织参数,调用Set方法
						methodName = String.format("set%s%s", fieldName.substring(0, 1).toUpperCase(),fieldName.substring(1));
						method = clazz.getMethod(methodName, f.getType());
						
					}catch(Exception e){
						System.out.println("在"+clazz+" 中找不到   "+methodName+" 方法,异常为:"+e);
						continue;
					}
					
					Object object = null;
					try{
						 object = executeQuery.getObject(fieldName);
					}catch(Exception e){
						System.out.println("没有找不到   "+methodName+" 字段,异常为:"+e);
						continue;
					}
					
					if(object==null)
						continue;
					
					//把值类型转为String,再转给参数的相应类型。
					String objStr = object.toString();
					
					
					//日期转换
					if(f.getType().getName().contains("Date")){
						Date date = DateConverter(objStr);
						
						method.invoke(instance, date);
						continue;
					}
					
 					Constructor constructor = f.getType().getConstructor(String.class);
 					object = constructor.newInstance(objStr);
					method.invoke(instance, object);
				}
				
				arrayList.add(instance);
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		return arrayList;
	}
	
	/*日期类型转换器*/
	public static Date DateConverter(String source){
		SimpleDateFormat sdf = new SimpleDateFormat(dateForma);
		Date parse;
		try {
			parse = sdf.parse(source);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		return parse;
	}
}

源代码下载:点击打开链接


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自主封装的PHP ORM框架,面向对象的PDO数据库操作,API框架,支持Get/Post/Put/Delete多种请求方式。 代码示例: <?php use Models\User; require '../application.php'; require '../loader-api.php'; //适合查询,如:获取用户列表或者单个用户信息 execute_request(HttpRequestMethod::Get, function() { $action = request_action(); //判断是否存在 if ($action == 1) { list($type, $value) = filter_request(array( request_int('type', 1, 2, 3), //1.用户名 2.邮箱 3.手机号 request_string('value'))); $type_field_map = array( 1 => User::$field_username, 2 => User::$field_email, 3 => User::$field_phone ); if ($type == 2 && !is_email($value) || $type == 3 && !is_mobilephone($value)) { die_error(USER_ERROR, $type_field_map[$type]['name'] . '格式无效'); } $user = new User(); $user->set_where_and($type_field_map[$type], SqlOperator::Equals, $value); $result = $user->exists(create_pdo()); echo_result($result ? 1 : 0); //存在返回1,不存在返回0 } //查询单条信息 if ($action == 2) { list($userid) = filter_request(array( request_userid())); //查询单条数据 $user = new User($userid); //set_query_fields可以指定查询字段,下面两种写法均可 //$user->set_query_fields('userid, username, email'); //$user->set_query_fields(array(User::$field_userid, User::$field_username, User::$field_email)); //还可设置where条件进行查询 //$user->set_where_and(User::$field_status, SqlOperator::Equals, 3); //$user->set_where_and(User::$field_truename, SqlOperator::IsNullOrEmpty); //$user->set_where_and(User::$field_age, SqlOperator::In, array(27, 29)); //$user->set_where_and(User::$field_regtime, SqlOperator::LessThan, '-6 month'); //创建数据库连接 $db = create_pdo(); $result = $user->load($db, $user); //也可以用Model类的静态方法 //$result = Model::load_model($db, $user, $user); if (!$result[0]) die_error(PDO_ERROR_CODE, '获取用户信息时数据库错误'); if (!$user) di
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值