- 利用反射简化查询代码,并做到通用
- 增强通用查询,融入分页元素
- junit
利用反射简化查询代码,并做到通用
增强通用查询,融入分页元素
junit
package com.zhulinjun.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 提供了一组获得或关闭数据库对象的方法 * */ public class DBAccess { private static String driver; private static String url; private static String user; private static String password; static {// 静态块执行一次,加载 驱动一次 try { InputStream is = DBAccess.class .getResourceAsStream("config.properties"); Properties properties = new Properties(); properties.load(is); driver = properties.getProperty("driver"); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("pwd"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 获得数据连接对象 * * @return */ public static Connection getConnection() { try { Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } public static void close(ResultSet rs) { if (null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Statement stmt) { if (null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn) { if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn, Statement stmt, ResultSet rs) { close(rs); close(stmt); close(conn); } public static boolean isOracle() { return "oracle.jdbc.driver.OracleDriver".equals(driver); } public static boolean isSQLServer() { return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver); } public static boolean isMysql() { return "com.mysql.cj.jdbc.Driver".equals(driver); } public static void main(String[] args) { Connection conn = DBAccess.getConnection(); System.out.println(conn); DBAccess.close(conn); System.out.println("isOracle:" + isOracle()); System.out.println("isSQLServer:" + isSQLServer()); System.out.println("isMysql:" + isMysql()); System.out.println("数据库连接(关闭)成功"); } }
package com.zhulinjun.util; public class StringUtils { // 私有的构造方法,保护此类不能在外部实例化 private StringUtils() { } /** * 如果字符串等于null或去空格后等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isBlank(String s) { boolean b = false; if (null == s || s.trim().equals("")) { b = true; } return b; } /** * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isNotBlank(String s) { return !isBlank(s); } }
package com.zhulinjun.entity; public class Book { private int bid; private String bname; private float price; @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; } public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
package com.zhulinjun.dao; import java.util.List; import org.junit.Test; import com.zhulinjun.entity.Book; import com.zhulinjun.util.BaseDao; import com.zhulinjun.util.PageBean; import com.zhulinjun.util.StringUtils; /** * 思考: bookDao:操作的是书籍表 代码重复 Connection con=DBAccess.getConnection(); * java.sql.PreparedStatement ps = con.prepareStatement(sql); ResultSet * rs=ps.executeQuery(); * 流程重复 * 1.创建表对应的实体类对象 * 2.将查询出来的结果集添加到实例化对象的属性中 * 3.已经被填充的实体对象,加入到集合中 while(rs.next()){ Book b=new Book(); * b.setBid(rs.getInt("bid")); b.setBname(rs.getString("bname")); * b.setPrice(rs.getFloat("price")); lst.add(b); } */ public class BookDao extends BaseDao<Book> { // public List<Book> list(Book book,PageBean pageBean) throws Exception{ List<Book> lst=new ArrayList<Book>(); // Connection con=DBAccess.getConnection(); // String sql="select * from t_mvc_book where 1=1"; // String bname = book.getBname(); // if(com.zhulinjun.util.StringUtils.isNotBlank(bname)) { // sql+="and bname like '% "+bname+" %' "; // } // java.sql.PreparedStatement ps = con.prepareStatement(sql); // ResultSet rs=ps.executeQuery(); // while(rs.next()){ // Book b=new Book(); // b.setBid(rs.getInt("bid")); // b.setBname(rs.getString("bname")); // b.setPrice(rs.getFloat("price")); // lst.add(b); // } // return lst; // } public List<Book> list(Book book, PageBean pageBean) throws Exception { String sql = "select * from t_mvc_book where 1=1 "; String bname = book.getBname(); if (StringUtils.isNotBlank(bname)) { System.out.println("----"); sql += " and bname like '%" + bname + "%' "; } return super.excuteQuery(sql, Book.class, pageBean); } // public static void main(String[] args) throws Exception { // BookDao bookDao=new BookDao(); // Book book =new Book(); // PageBean pageBean=new PageBean(); // List<Book> list =bookDao.list(book, pageBean); // for (Book b : list) { // System.out.println(b); // } @Test public void text1() throws Exception { BookDao bookDao = new BookDao(); System.out.println("test1..."); Book book = new Book(); book.setBname("圣墟"); PageBean pageBean = new PageBean(); List<Book> list = bookDao.list(book, pageBean); for (Book b : list) { System.out.println(b); } System.out.println(pageBean); } @Test public void text2() throws Exception { BookDao bookDao = new BookDao(); System.out.println("test2..."); Book book = new Book(); PageBean pageBean = new PageBean(); List<Book> list = bookDao.list(book, pageBean); for (Book b : list) { System.out.println(b); } } @Test public void text3() throws Exception { System.out.println("test3..."); BookDao bookDao = new BookDao(); Book book = new Book(); book.setBname("圣墟"); PageBean pageBean = new PageBean(); // pageBean.setPagination(false);//false为不进行分页 // pageBean.setPage(2);//查询第二页 List<Book> list = bookDao.list(book, pageBean); for (Book b : list) { System.out.println(b); } } }
package com.zhulinjun.util; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class BaseDao<T> { public List<T> excuteQuery(String sql,Class clz,PageBean pageBean) throws Exception{ List<T> lst=new ArrayList<T>(); Connection con=null; PreparedStatement ps =null; ResultSet rs=null; // sql=select * from t_mvc_book where bname like '%圣墟%' // countSql=select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t // pageSql=select * from t_mvc_book where bname like '%圣墟%' limit 0,10 if(pageBean!=null && pageBean.isPagination()){ String countSQL = getCountSQL(sql); con=DBAccess.getConnection(); ps = con.prepareStatement(countSQL); rs=ps.executeQuery(); if(rs.next()) { pageBean.setTotal(rs.getObject("n").toString()); } String pageSQL = getPageSQL(sql,pageBean); con=DBAccess.getConnection(); ps = con.prepareStatement(pageSQL); rs=ps.executeQuery(); }else { con=DBAccess.getConnection(); ps = con.prepareStatement(sql); rs=ps.executeQuery(); } while(rs.next()){ T t=(T) clz.newInstance(); // 拿到class对应的所有属性对象 Field[] fields = clz.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); // System.out.println(f.getName()); f.set(t, rs.getObject(f.getName())); } lst.add(t); // Book b=new Book(); // b.setBid(rs.getInt("bid")); // b.setBname(rs.getString("bname")); // b.setPrice(rs.getFloat("price")); // lst.add(b); } return lst; } /** * 拼接出最终展示出的数据sql * @param sql 原生sql * @param pageBean * @return */ private String getPageSQL(String sql, PageBean pageBean) { // TODO Auto-generated method stub return sql+" limit "+pageBean.getStartIndex()+ ","+pageBean.getRows(); } /** * 拼接出查询符合条件的总记录数sql * @param sql * @return */ private String getCountSQL(String sql) { // TODO Auto-generated method stub return "select count(1) as n from ("+sql+") t "; } }