package project02_Order_management.util;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; /**
* 封装对数据库进行--连接/增/删/改/查/
*
* @author MartinDong
*
* @param <T>
* 要操作的数据对象
*/
public class BaseDAOUtil<T> {
/**
* 声明数据库连接对象
*/
private static Connection connection;
/**
* 声明预处理对象
*/
private static PreparedStatement preparedStatement;
/**
* 声明sql语句返回结果集对象
*/
private static ResultSet resultSet; /**
* 载入默认的configuration.properties资源文件
*
* @return
*/
public static Properties getProperties() {
return getProperties(null);
} /**
* 载入资源文件
*
* @param propertyName
* 传入要载入的资源文件名称称;
* @return properties 返回一个属性配置对象
*/
public static Properties getProperties(String propertyName) {
/**
* 设置配置资源文件的默认文件名称
*/
if (propertyName == null) {
propertyName = "configuration.properties";
}
/**
* 声明属性文件类,读取配置使用
*/
Properties properties = new Properties();
try {
/**
* currentThread()是Thread的一个静态方法。返回的是当前的进程对象
*/
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream(propertyName));
} catch (IOException e) {
System.out.println(propertyName + "文件载入出现错误!");
e.printStackTrace();
}
return properties;
} /**
* 获取默认的数据库连接对象
*
* @return
*/
public static Connection getConnection() {
return getConnection(getProperties());
} /**
* 获取数据库连接对象
*
* @param properties
* 传入已经配置好的属性配置对象;
* @return <b>connection</b> 数据库连接对象
*/
public static Connection getConnection(Properties properties) {
if (connection == null) {
/**
* 载入数据库驱动文件
*/
try {
Class.forName(properties.getProperty("jdbc.driver"));
/**
* 创建数据库连接对象
*/
try {
connection = DriverManager.getConnection(
properties.getProperty("jdbc.url"),
properties.getProperty("jdbc.user"),
properties.getProperty("jdbc.password"));
System.out.println("数据库连接成功>>>>>>>>>>>");
} catch (SQLException e) {
System.out.println("数据库连接參数错误!");
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
System.out.println("缺少数据库驱动文件:"
+ properties.getProperty("jdbc.driver") + "!");
e.printStackTrace();
}
}
return connection;
} /**
* 释放资源的方法;<br>
*
* @param releaseSet
* @param preparedStatement
* @param connection
*/
public static void release(ResultSet releaseSet,
PreparedStatement preparedStatement, Connection connection) {
if (releaseSet != null) {
try {
releaseSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} // /////////////////////////////////CRUD基础业务/////////////////////////////
/**
* 採用默认的连接,而且数据库表名与实体类名一致[不区分大写和小写]
*
* @param entity
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void save(T entity) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException, SQLException {
save(entity, getConnection());
} /**
* 採用数据库表名与实体类名一致[不区分大写和小写]外部传入数据库连接;
*
* @param entity
* @param connection
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public void save(T entity, Connection connection)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, SQLException {
save(entity, connection, null);
} /**
* 将实体存入数据库
*
* @param entity
* 要操作的数据对象
* @param connection
* 传数据库连接
* @param tableName
* 要操作的表的名称,假设传入null,则对传入的对象名称一致的表进行操作
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void save(T entity, Connection connection, String tableName)
throws SQLException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
/**
* 获取操作实体的类型
*/
Class<? extends Object> clazz = entity.getClass();
/**
* 获取传入实体的全部公开的方法;
*/
Method[] methods = clazz.getDeclaredMethods();
/**
* 获取传入实体中的全部公开的的属性
*/
Field[] fields = clazz.getDeclaredFields();
/**
* 假设没有输入指定的数据表名酒採用类名进行操作
*/
if (tableName == null) {
tableName = clazz.getSimpleName().toLowerCase();
}
/**
* 拼接类中的属性字段,即数据表中的字段名
*/
String fieldsName = "";
/**
* 占位符的设置
*/
String placeholder = "";
for (int i = 0; i < fields.length; i++) {
fieldsName = fieldsName + fields[i].getName() + ",";
placeholder = placeholder + "?" + ",";
}
/**
* 去除多余的标点
*/
fieldsName = fieldsName.substring(0, fieldsName.length() - 1);
placeholder = placeholder.substring(0, placeholder.length() - 1);
/**
* 拼接sql语句
*/
String sql = "insert into " + tableName + "(" + fieldsName + ")"
+ " values " + "(" + placeholder + ")";
System.out.println(sql); /**
* 预编译sql语句
*/
PreparedStatement pst = connection.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 propertyObj = methods[k].invoke(entity);
/**
* 为指定的占位符进行赋值
*/
pst.setObject(index++, propertyObj);
}
}
}
/**
* 运行已经载入的sql语句
*/
pst.executeUpdate();
} /**
* 使用默认的数据库连接进行删除,传入的对象
*
* @param entity
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public void delete(T entity) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException, SQLException {
deleteById(entity, getConnection());
} /**
* 使用传入的数据库连接,删除指定的对象.
*
* @param entity
* @param connection
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public void deleteById(T entity, Connection connection)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, SQLException { delete(entity, connection, null);
} /**
*
* @param entity
* 传入操作的对象实体
* @param connection
* 传入数据库连接对象
* @param id
* 要删除数据的id
* @param tableName
* 要操作的表的名称,假设传入null,则对传入的对象名称一致的表进行操作
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*
*/
public void delete(T entity, Connection connection, String tableName)
throws SQLException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Class<? extends Object> clazz = entity.getClass();
Method[] methods = clazz.getDeclaredMethods();
Field[] fields = clazz.getDeclaredFields();
if (tableName == null) {
tableName = clazz.getSimpleName().toLowerCase();
}
String sql = "delete from " + tableName + " where id=?";
System.out.println(sql);
PreparedStatement pst = connection.prepareStatement(sql); Object id = null;
for (int i = 0; i < fields.length; i++) {
for (int j = 0; j < methods.length; j++) {
if ("getId".equalsIgnoreCase(methods[j].getName())) {
id = methods[j].invoke(entity);
}
}
}
pst.setObject(1, id);
pst.executeUpdate();
} /**
* 使用默认的数据库连接改动传入的对象.
*
* @param entity
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public void update(T entity) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException, SQLException {
update(entity, getConnection());
} /**
* 使用传入的数据库连接进行数据库改动;
*
* @param entity
* @param connection
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public void update(T entity, Connection connection)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, SQLException {
update(entity, connection, null);
} /**
*
* @param entity
* 传入操作的对象实体
* @param connection
* 传入数据库连接对象
* @param tableName
* 要操作的表的名称,假设传入null,则对传入的对象名称一致的表进行操作
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public void update(T entity, Connection connection, String tableName)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, SQLException {
Class<? extends Object> clazz = entity.getClass();
Method[] methods = clazz.getDeclaredMethods();
Field[] fields = clazz.getDeclaredFields();
if (tableName == null) {
tableName = clazz.getSimpleName().toLowerCase();
}
String fieldsName = "";
// 创建id字段的默认数据
Object id = 1;
// 循环遍历以获取的公开的属性
for (int i = 0; i < fields.length; i++) {
// 嵌套循环,比較公开属性名经过拼接后和公开的方法名进行匹配
for (int j = 0; j < methods.length; j++) {
// 使用属性名+get进行拼接
String getFieldName = "get" + fields[i].getName();
if (getFieldName.equalsIgnoreCase(methods[j].getName())) {
// 拼接更行sql语句中的set字段,并用占位符
fieldsName = fieldsName + fields[i].getName() + "=? ,";
}
// 获取id字段的值
if ("getId".equalsIgnoreCase(methods[j].getName())) {
id = methods[j].invoke(entity);
}
}
}
fieldsName = fieldsName.substring(0, fieldsName.length() - 1);
String sql = "update " + tableName + " set " + fieldsName
+ " where id=?";
System.out.println(sql);
PreparedStatement pst = connection.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 propertyObj = methods[k].invoke(entity);
// 为指定的占位符进行赋值
pst.setObject(index++, propertyObj);
}
}
}
pst.setObject(index++, id);
pst.execute();
} /**
* 使用默认的数据库连接查询指定的id数据
*
* @param entity
* @param id
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public T findById(T entity, Integer id) throws InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, SQLException {
return findById(entity, null, id);
} /**
*
* 使用传入的数据库连接以及传入的id查询数据;
*
* @param entity
* @param connection
* @param id
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public T findById(T entity, Connection connection, Integer id)
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, SQLException {
return findById(entity, connection, id, null);
} /**
*
* 依据id查询数据
*
* @param entity
* 查询的实体对象
* @param connection
* 数据库连接对象
* @param id
* 查询的id
* @param tableName
* 操作的数据库表名
* @return 返回一个查询结果对象
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public T findById(T entity, Connection connection, Integer id,
String tableName) throws SQLException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
Class<? extends Object> clazz = entity.getClass();
Method[] methods = clazz.getDeclaredMethods();
Field[] fields = clazz.getDeclaredFields();
// 声明查询的结果对象
T resultObject = null;
if (tableName == null) {
tableName = clazz.getSimpleName().toLowerCase();
}
String sql = "select * from " + tableName + " where id=? ";
System.out.println(sql);
PreparedStatement pst = connection.prepareStatement(sql);
pst.setObject(1, id);
ResultSet resultSet = pst.executeQuery();
if (resultSet.next()) {
resultObject = (T) clazz.newInstance();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName(); Object fieldObject = resultSet.getObject(i + 1);
if (fieldObject == null) {
fieldObject = "null";// 防止数据为null时引发空指针异常
}
for (int j = 0; j < methods.length; j++) {
if (("set" + fieldName).equalsIgnoreCase(methods[j]
.getName())) {
methods[j].invoke(resultObject,
resultSet.getObject(fieldName));
}
}
}
}
return resultObject;
} /**
* 使用默认的数据库连接进行数据查询
*
* @param entity
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public List<T> findAll(T entity) throws InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, SQLException {
return findAll(entity, getConnection());
} /**
* 使用传入的数据库连接进行数据查询
*
* @param entity
* @param connection
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public List<T> findAll(T entity, Connection connection)
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, SQLException {
return findAll(entity, connection, null);
} /**
* 查询数据表全部的数据
*
* @param entity
* 查询的实体对象
* @param connection
* 数据库连接对象
* @param tableName
* 操作的数据库表名
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public List<T> findAll(T entity, Connection connection, String tableName)
throws SQLException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
Class<? extends Object> clazz = entity.getClass();
Method[] methods = clazz.getDeclaredMethods();
Field[] fields = clazz.getDeclaredFields();
// 声明查询的结果对象
List<T> resultObjects = new ArrayList<T>();
if (tableName == null) {
tableName = clazz.getSimpleName().toLowerCase();
}
String sql = "select * from " + tableName;
System.out.println(sql);
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet resultSet = pst.executeQuery();
while (resultSet.next()) {
T resultObject = (T) clazz.newInstance();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
Object fieldObject = resultSet.getObject(i + 1);
if (fieldObject == null) {
fieldObject = "null";
}
for (int j = 0; j < methods.length; j++) {
if (("set" + fieldName).equalsIgnoreCase(methods[j]
.getName())) {
methods[j].invoke(resultObject,
resultSet.getObject(fieldName));
} }
}
resultObjects.add(resultObject);
}
return resultObjects;
} public List<T> query(T entity, Connection connection, String tableName,
String sql) { return null;
} /**
* 一个须要用户手动输入sql和參数语句的:增/删/改/的操作
*
* @param sql
* @param args
* @return
*/
public static int upDate(String sql, Object[] args) {
try {
preparedStatement = getConnection().prepareStatement(sql);
for (int i = 1; i <= args.length; i++) {
preparedStatement.setObject(i, args[i - 1]);
}
return preparedStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
} /**
* 传入自己定义的sql语句和參数进行查询;
*
* @param sql
* sql语句
* @param args
* 传入的參数条件
* @return 返回一个set集合
*/
public static ResultSet getObject(String sql, Object[] args) {
System.out.println(sql);
try {
preparedStatement = JDBCUtil.getConnection().prepareStatement(sql);
if (args != null) {
for (int i = 1; i <= args.length; i++) {
preparedStatement.setObject(i, args[i - 1]);
}
}
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultSet;
} }

configuration.properties配置文件

jdbc.url=jdbc\:mysql\://localhost\:3306/order_manager
jdbc.user=root
jdbc.password=admin
jdbc.driver=com.mysql.jdbc.Driver

仿照hibernate封装的一个对数据库操作的jdbc工具类的更多相关文章

  1. MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  2. MySQL数据库学习笔记(十)----JDBC事务处理、封装JDBC工具类

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  3. DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)

    DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类) 一.DAO模式简介 DAO即Data Access Object,数据访问接口.数据访问:故名思义就是与数据库打交道.夹在业务逻辑与数据 ...

  4. 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!

    转载自:https://github.com/whvcse/RedisUtil 代码 ProtoStuffSerializerUtil.java import java.io.ByteArrayInp ...

  5. MySQL JDBC事务处理、封装JDBC工具类

    MySQL数据库学习笔记(十)----JDBC事务处理.封装JDBC工具类 一.JDBC事务处理: 我们已经知道,事务的概念即:所有的操作要么同时成功,要么同时失败.在MySQL中提供了Commit. ...

  6. c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习

    c#中@标志的作用   参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

  7. JDBC_13_封装JDBC工具类

    封装JDBC工具类 代码: import java.sql.*; /** * JDBC工具类,简化JDBC编程 */ public class DBUtil { //工具类中的构造方法都是私有的,因为 ...

  8. jdbc 11: 封装自己的jdbc工具类

    jdbc连接mysql,封装自己的jdbc工具类 package com.examples.jdbc.utils; import java.sql.*; import java.util.Resour ...

  9. 【转载】C#工具类:实现文件操作File的工具类

    在应用程序的开发中,文件操作的使用基本上是必不可少的,FileStream类.StreamWriter类.Directory类.DirectoryInfo类等都是文件操作中时常涉及到的类,我们可以通过 ...

随机推荐

  1. Ubuntu下安装MySQL及简单操作

    Ubuntu上安装MySQL非常简单只需要几条命令就可以完成. 1. sudo apt-get install mysql-server 2. apt-get isntall mysql-client ...

  2. sqlite3错误码整理

    #define SQLITE_OK /* 成功 | Successful result */ /* 错误码开始 */ #define SQLITE_ERROR /* SQL错误 或 丢失数据库 | S ...

  3. Win8交互UX——笔交互

    针对触摸输入优化 Window 应用商店应用设计,并在默认情况下获得基本的笔支持. 本主题介绍笔交互的设计注意事项.有关实现笔交互的信息,请参阅响应笔和触笔交互. 笔交互 通过使用笔创建手写便笺.绘图 ...

  4. 【大数据系列】安装Ambari

    一.Ambari简介 The Apache Ambari project is aimed at making Hadoop management simpler by developing soft ...

  5. Android 框架

    1. https://github.com/wyouflf/xUtils xUtils简介 xUtils 包含了很多实用的android工具. xUtils 最初源于Afinal框架,进行了大量重构, ...

  6. Kotlin 资料

    https://kotlinlang.org/docs/reference/  官方 https://github.com/JetBrains/kotlin/releases   Kotlin SDK ...

  7. Linux 开启VNCSERVER

    尽管我们可以使用 SSH连接远程通过字符界面来操作Linux,但是对于更多熟悉图形人来说是很不方便的,因此开启Linux的远程桌面还是很有必要的.目前有两种比较流 行的方式:XDM(X display ...

  8. linux系统下网络主-备份策略之网卡bond技术

    操作系统:CentOS Linux release 7.1.1503 (Core) 网卡适配器: eno1.eno2 bonding类型:mode=1 (active-backup),主-备份策略 网 ...

  9. spring配置多视图解析器

    最近做一个小项目(移动端),自己搭了个简单的SSM框架(spring + spring MVC + Mybitis),展示层本来选用的是jsp,各方便都已经搭建好,结果发现有些页面需要用到H5的一些功 ...

  10. APM飞控的使用心得

    硬件资源:APM,F450四轴机架,大疆电调和电机,富斯i6控和接收机. 刚开始的步骤都是大同小异,首先可以按照这个链接上面的步骤一步步的执行:http://tieba.baidu.com/p/297 ...