无论是mybatis还是hibernate都是只是将JDBC进行了封装,于是乎参考了老师的套路自己也封装了一些功能。说不定对于以后学习mybatis和hibernate的时候会有帮助。
功能主要包括:
本工具类包含了JDBC的常用的增删改查操作查询包括:单表查询单表条件查询多表查询多表联合加条件查询分页查询满足条件的记录数根据主键查询等原生的JDBC操作…上代码:
package com.util; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.druid.pool.DruidPooledConnection; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.*; public class JDBCUtil { private static DruidDataSource dataSource; private static Properties properties; static { InputStream inputStream = com.util.JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties"); properties = new Properties(); try { properties.load(inputStream); dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //获取数据库连接 public static Connection getConnection(){ DruidPooledConnection connection = null; try { connection = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return connection; } //关闭流 增删改 public static void close(Connection connection, PreparedStatement ps){ if(connection != null){ //alt+enter try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps != null){ //alt+enter try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } //关闭流 增删改 public static void close(Connection connection, PreparedStatement ps,ResultSet rs){ if(connection != null){ //alt+enter try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps != null){ //alt+enter try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null){ //alt+enter try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } //增删改通用方法 public static boolean update(Connection connection,String sql,Object...params){ //获取连接 PreparedStatement ps = null; try{ ps = connection.prepareStatement(sql); //设置参数 for(int i = 0; i < params.length; i++){ ps.setObject(i + 1,params[i]); } int result = ps.executeUpdate(); return result > 0; }catch (Exception e){ e.printStackTrace(); } return false; } //通用的查询方法 单表不带条件的,带条件的 public static <T> List<T> queryByCondition(Class<T> clazz,String sql,Object...params){ Connection conn = com.util.JDBCUtil.getConnection(); PreparedStatement ps = null; ResultSet rs = null; List<T> list= new ArrayList<>(); try{ ps = conn.prepareStatement(sql); //设置参数 for(int i = 0; i < params.length; i++){ ps.setObject(i + 1,params[i]); } rs = ps.executeQuery(); //需要知道查询结果集的列名 ResultSetMetaData metaData = rs.getMetaData(); //用于存储每次查询列的结果集 Map<String,Object> data = new HashMap<>(); //遍历查询的结果集 while(rs.next()){ T t = clazz.newInstance(); for(int i = 0; i < metaData.getColumnCount(); i++){ String name = metaData.getColumnName(i+1).toLowerCase(); Object value = rs.getObject(name); data.put(name,value); } ConvertUtils.register(new Converter() { //o:页面输入的日期 @Override public Object convert(Class aClass, Object o) { //判断日期是否null ***** "" if(o == null){ return null; } //指定页面输入的日期格式 String pattern = "yyyy-MM-dd"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { return sdf.parse(o.toString()); } catch (ParseException e) { e.printStackTrace(); } return null; } }, Date.class); //将Map中的数据放入到对象中 BeanUtils.populate(t,data); list.add(t); } }catch (Exception e){ e.printStackTrace(); } return list; } //根据主键查询 //Serializable:可以序列化 可以通过网络传输对象 public static <T> T queryByPrimaryKey(Class<T> clazz, String sql, Serializable primaryKey){ Connection connection = getConnection(); PreparedStatement ps = null; ResultSet rs = null; T t = null; try{ //根据字节码得到该对象的实例 //要求:原类的构造方法必须是public // t = clazz.newInstance(); //如果构造方法私有化 Constructor<T> constructor = clazz.getDeclaredConstructor(); t = constructor.newInstance(); // System.out.println("t======"+t); ps = connection.prepareStatement(sql); ps.setObject(1,primaryKey); rs = ps.executeQuery(); //元数据 ResultSetMetaData metaData = rs.getMetaData(); if(!rs.next()) return null; for(int i = 0; i < metaData.getColumnCount(); i++){ String columnName = metaData.getColumnName(i + 1).toLowerCase(); Object value = rs.getObject(columnName); BeanUtils.setProperty(t,columnName,value); } }catch (Exception e){ e.printStackTrace(); } // System.out.println("t="+t); //t是通过反射 return t; } //查询总记录数(包含条件) 为分页服务的 limit a,b //a = (page - 1) * b public static int count(String sql,Object...params){ Connection connection = getConnection(); PreparedStatement ps = null; ResultSet rs = null; try{ ps = connection.prepareStatement(sql); for(int i = 0 ; i < params.length; i++){ ps.setObject(i + 1,params[i]); } rs = ps.executeQuery(); rs.next(); return rs.getInt(1); }catch (Exception e){ e.printStackTrace(); } return 0; } /* 多表带条件和不带条件的查询结果集封装 该查询结果集全部封装到map中,和实体类没有关系 */ public static List<Map<String,Object>> queryByCondition(String sql,Object...params){ Connection connection = getConnection(); PreparedStatement ps = null; ResultSet rs = null; List<Map<String,Object>> list = new ArrayList<>(); try { ps = connection.prepareStatement(sql); //设置参数 for(int i = 0; i < params.length; i++){ ps.setObject(i + 1,params[i]); } rs = ps.executeQuery(); //需要知道查询结果集的列名 ResultSetMetaData metaData = rs.getMetaData(); //遍历查询的结果集 while(rs.next()){ //用于存储每次查询列的结果集 Map<String,Object> data = new HashMap<>(); for(int i = 0; i < metaData.getColumnCount(); i++){ String name = metaData.getColumnName(i+1).toLowerCase(); Object value = rs.getObject(name); data.put(name,value); } list.add(data); } }catch (Exception e){ e.printStackTrace(); } return list; } //分页多条件复杂查询结果集封装,适合单表和多表查询 //将所有查询结果集都放到一个List<Map<>> public static List<Map<String,Object>> pagination(String page,int pageSize,String sql,Object...params){ int pageNum = 0; if(page == null){ pageNum = 1; }else{ pageNum = Integer.parseInt(page); } sql += " limit "+(pageNum-1)*pageSize+","+pageSize+""; return queryByCondition(sql,params); } }下面是db.properties(放在src目录下面)
url=jdbc:mysql://localhost:3306/yyc?serverTimeZone:UTC #这个可以缺省的,会根据url自动识别 driverClassName=com.mysql.jdbc.Driver username=root password=root ##数据库连接池 ##初始连接数,默认0 initialSize=10 #最大连接数,默认8 maxActive=30 #最小闲置数 minIdle=10 #获取连接的最大等待时间,单位毫秒 maxWait=2000 #缓存PreparedStatement,默认false poolPreparedStatements=true #缓存PreparedStatement的最大数量,默认-1(不缓存)。大于0时会自动开启缓存PreparedStatement,所以可以省略上一句设置 maxOpenPreparedStatements=20