仿照hibernate封装的一个对数据库操作的jdbc工具类
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工具类的更多相关文章
- MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- MySQL数据库学习笔记(十)----JDBC事务处理、封装JDBC工具类
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)
DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类) 一.DAO模式简介 DAO即Data Access Object,数据访问接口.数据访问:故名思义就是与数据库打交道.夹在业务逻辑与数据 ...
- 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!
转载自:https://github.com/whvcse/RedisUtil 代码 ProtoStuffSerializerUtil.java import java.io.ByteArrayInp ...
- MySQL JDBC事务处理、封装JDBC工具类
MySQL数据库学习笔记(十)----JDBC事务处理.封装JDBC工具类 一.JDBC事务处理: 我们已经知道,事务的概念即:所有的操作要么同时成功,要么同时失败.在MySQL中提供了Commit. ...
- 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 ...
- JDBC_13_封装JDBC工具类
封装JDBC工具类 代码: import java.sql.*; /** * JDBC工具类,简化JDBC编程 */ public class DBUtil { //工具类中的构造方法都是私有的,因为 ...
- jdbc 11: 封装自己的jdbc工具类
jdbc连接mysql,封装自己的jdbc工具类 package com.examples.jdbc.utils; import java.sql.*; import java.util.Resour ...
- 【转载】C#工具类:实现文件操作File的工具类
在应用程序的开发中,文件操作的使用基本上是必不可少的,FileStream类.StreamWriter类.Directory类.DirectoryInfo类等都是文件操作中时常涉及到的类,我们可以通过 ...
随机推荐
- Android开发懒人库 -- ButterKnife (转载)
ButterKnife:8.1.0的使用 http://www.jianshu.com/p/0392199a682b http://www.cnblogs.com/flyme/p/4517560. ...
- IOS设计模式第五篇之装饰设计模式的代理设计模式
版权声明:原创作品,谢绝转载!否则将追究法律责任. 代理: 另一个装饰设计模式,代理,是一个代表或者协调另一个对象的行为机制.例如当你用一个tableView,你必须实现他里面的一个tableView ...
- mysqlint类型的长度值mysql在建表的时候int类型后的长度代表什么
详解mysql int类型的长度值 mysql在建表的时候int类型后的长度代表什么 是该列允许存储值的最大宽度吗 为什么我设置成int(1), 也一样能存10,100,1000呢. 当时我虽然知道i ...
- django进阶-查询(适合GET4以上人群阅读)
前言: 下篇博客写关于bootstrap... 一.如何在脚本测试django from django.db import models class Blog(models.Model): name ...
- 深入理解 Neutron -- OpenStack 网络实现(4):网络名字空间
问题导读1.如何查看网络名字空间?2.网络名字空间开头的名字有什么规律?3.dhcp服务是如何实现的?4.router的实现是通过iptables进行的是否正确?5.SNAT和DNAT规则有什么作用? ...
- css方法 - 移动端h5在iphonex的适配
@media only screen and (device-width:375px) and (device-height:812px) and (-webkit-device-pixel-rati ...
- sencha touch 2.3.1 list emptyText不显示
如图所示,有时候没有取到任何的数据. 那么我们就需要显示没有获取到内容这一类提示,显示内容通常通过emptyText这个属性来配置. 但是在sencha touch 2.3.1之中有可能会出问题,所以 ...
- mysql优化之伪哈希索引
想法非常简单,在标准的B-Tree索引上创建一个伪哈希索引.它和真正的哈希索引不是一回事,因为它还是使用B-Tree索引进行查找.然而,它将会使用键的哈希值进行查找,而不是键自身.你所要做的事情就是在 ...
- mac设置文件权限问题
在使用mac时,经常我们遇到相关文件不能使用的情况,其实大多数情况都是,文件权限问题. 文件或目录的访问权限分为只读,只写和可执行三种.以文件为例,只读权限表示只允许读其内容,而禁止对其做任何的更改操 ...
- python标准库和第三方库的区别
1.python的标准库是随着pyhon安装的时候默认自带的库. 2.python的第三方库,需要下载后安装到python的安装目录下,不同的第三方库安装及使用方法不同. 3.它们调用方式是一样的,都 ...