JDBC辅助类封装 及应用

 

一:代码图解:

image

二:配置文件:

  1 driverClassName=com.mysql.jdbc.Driver
  2 url=jdbc:mysql://127.0.0.1:3306/xlzj_sh_new?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
  3 username=root
  4 password=123456
  5 filters=stat
  6 initialSize=10
  7 maxActive=200
  8 maxWait=60000
  9 #maxIdle=15
 10 minIdle=10
 11 timeBetweenEvictionRunsMillis=60000
 12 minEvictableIdleTimeMillis=300000
 13 validationQuery=SELECT 'x'
 14 testWhileIdle=true
 15 testOnBorrow=false
 16 testOnReturn=false
 17 poolPreparedStatements=false
 18 maxPoolPreparedStatementPerConnectionSize=20
 19 #u7981u7528u5BF9u4E8Eu957Fu65F6u95F4u4E0Du4F7Fu7528u7684u8FDEu63A5u5F3Au5236u5173u95EDu7684u529Fu80FD
 20 removeAbandoned=false
 21 #u8D85u8FC730u5206u949Fu5F00u59CBu5173u95EDu7A7Au95F2u8FDEu63A5uFF0Cu7531u4E8EremoveAbandonedu4E3AfalseuFF0Cu8FD9u4E2Au8BBEu7F6Eu9879u4E0Du518Du8D77u4F5Cu7528
 22 removeAbandonedTimeout=1800
 23 #u5C06u5F53u524Du5173u95EDu52A8u4F5Cu8BB0u5F55u5230u65E5u5FD7uFF0Cu7531u4E8EremoveAbandonedu4E3AfalseuFF0Cu8FD9u4E2Au8BBEu7F6Eu9879u4E0Du518Du8D77u4F5Cu7528
 24 logAbandoned=true
 25 

三:获取配置文件信息

image

PathUtil.java

  1 package com.jacezhu.framework.utils.BeanUtil.pathUtil;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.FileInputStream;
  5 import java.io.InputStream;
  6 import java.net.URL;
  7 import java.util.Properties;
  8 
  9 /**
 10  *
 11 *      12 * 项目名称:text     13 * 类名称:PathUtil     14 * 类描述:   获取文件路径
 15 * 创建人: 刘军/shall_liu   16 * 创建时间:2015年11月17日 下午4:10:31     17 * 修改人:Administrator     18 * 修改时间:2015年11月17日 下午4:10:31     19 * 修改备注:     20 * @version      21 *      22  */
 23 public class PathUtil {
 24 	/**
 25 	 * 获取  获取人参文件的 路径
 26 	 * @return
 27 	 */
 28     public static String getPath(String fileName){
 29     	String path=getPath(getFileUrl(),  fileName);
 30 		return path;
 31     }
 32      /**
 33       * 获取:入参 properties配置文件里面的值(key_value)
 34       * @param FileName(*.properties <配置文件名称.properties>)
 35       * @return  properties 对象
 36       */
 37     public static Properties returnPropertiesValue(String FileName){
 38 		return readData(getPath(FileName));
 39 	}
 40 
 41 
 42     /**
 43      *
 44     * @Title: getPath   45     * @Description: (根据URl 获取指定文件的路径)
 46     * @param @param url
 47     * @param @return    设定文件   48     * @return String    返回类型   49     * @throws   50     * 创建者:刘军/shall_liu
 51     * 创建时间:2015年11月18日下午2:06:50
 52      */
 53     public static String getPath(URL url,String fileName){
 54 		String path = (url + fileName );
 55         int index=lookindex(path,'/');
 56         String newPath=path.substring(index+1, path.length());
 57 		return newPath;
 58     }
 59     /**
 60      *
 61     * @Title: getFileUrl   62     * @Description: (获取根目录路径)
 63     * @param @return    设定文件   64     * @return URL    返回类型   65     * @throws   66     * 创建者:刘军/shall_liu
 67     * 创建时间:2015年11月18日下午2:04:23
 68      */
 69     public static URL getFileUrl(){
 70     	URL url = ClassLoader.getSystemClassLoader().getResource("./");
 71 		return url;
 72     }
 73 
 74     /**
 75      * 获取 某个字符在某个字符串第一次出现的位置
 76      * @param string
 77      * @param s
 78      * @return
 79      */
 80 	public static int lookindex(String string, char s) {
 81 
 82 		int number = 0;
 83 		int index=-1;//-1 表示没有找到 
 84 		char arr[] = string.toCharArray();
 85 		for (int i = 0; i < arr.length; i++) {
 86 			if (arr[i] == s) {
 87 				number++;
 88 			}
 89 			if (number == 1) {
 90 				 index=i;
 91 				  return i;
 92 			}
 93 		}
 94 		return index;
 95 	}
 96 	/**
 97 	 *
 98 	* @Title: lookindex   99 	* @Description: (判断字符 c在 字符串 string中指定出现的index次数时该字符c在字符串string中的位置)
100 	* @param @param string
101 	* @param @param s
102 	* @param @param indexs
103 	* @param @return    设定文件  104 	* @return int    返回类型  105 	* @throws  106 	* 创建者:刘军/shall_liu
107 	* 创建时间:2015年11月18日下午1:59:27
108 	 */
109 	public static int lookindex(String string, char s,int indexs) {
110 		int number = 0;
111 		int index=-1;//-1 表示没有找到 
112 		char arr[] = string.toCharArray();
113 		for (int i = 0; i < arr.length; i++) {
114 			if (arr[i] == s) {
115 				number++;
116 			}
117 			if (number ==indexs) {
118 				 index=i;
119 				  return i;
120 			}
121 		}
122 		return index;
123 	}
124 	/**
125 	 *
126 	* @Title: counter  127 	* @Description: ( 判断字符串c在 字符串source中出现的总次数)
128 	* @param @param source
129 	* @param @param c
130 	* @param @return    设定文件  131 	* @return int    返回类型  132 	* @throws  133 	* 创建者:刘军/shall_liu
134 	* 创建时间:2015年11月18日下午1:57:29
135 	 */
136 	public static int counter(String source,String c){
137 		 int counter=0;
138 		 if(c ==null||c.trim().equals("")){
139 			   counter=0;
140 		 }else{
141 			if(!source.trim().equals("")&&source!=null){
142 				String[] newArray=source.split(c);
143 				counter=newArray.length-1;
144 			}
145 		 }
146 		return counter;
147 		}
148 
149 	public static void main(String[] args) {
150 		String path=getPath("dabase.properties");
151 		System.out.println(path);
152 	}
153 
154 
155 	/**
156 	 * 获取整个配置文件中的属性
157 	 *
158 	 * @param filePath
159 	 *            文件路径,即文件所在包的路径,例如:java/util/config.properties
160 	 */
161 	public static Properties readData(String filePath) {
162 		Properties props = new Properties();
163 		try {
164 			InputStream in = new BufferedInputStream(new FileInputStream(
165 					filePath));
166 			props.load(in);
167 			in.close();
168 			return props;
169 		} catch (Exception e) {
170 			e.printStackTrace();
171 			return null;
172 		}
173 	}
174 
175 
176 
177 }
178 

PropertiesConfig.java

  1 package com.jacezhu.framework.utils.BeanUtil.pathUtil;
  2 
  3 import java.io.InputStream;
  4 import java.util.Properties;
  5 
  6 /**
  7  * 主题:读取Config文件工具类 P
  8  *
  9  * @author 刘军/shell_liu 2015-4-14
 10  */
 11 public class PropertiesConfig {
 12 
 13 
 14 	/**
 15 	 *
 16 	 * @Title: getProperties   17 	 * @Description:
 18 	 *               (TestProperties.class.getClassLoader().getResourceAsStream
 19 	 *               ("db.properties" );
 20 	 *               类名.class.类加载器.从文件流中获取资源("放在程序根目录下的properties文件中的内容")
 21 	 *               loader: 载入程序;装货设备;装填器)   22 	 * @param @param fileName
 23 	 * @param @return    设定文件   24 	 * @return Properties    返回类型   25 	 * @throws   26 	 */
 27 	public static Properties getProperties(String fileName) {
 28 		/*
 29 		 * 从properties文件中读取文件思路: 1:声明对象:Properties props=new Properties();
 30 		 * 2:调用获取properties文件内容的流方法:props.load(inStream); 3:将src
 31 		 * /db.propreties以InputStream方式载入 inStream=
 32 		 * TestProperties.class.getClassLoader
 33 		 * ().getResourceAsStream("db.properties"); 4://读取props中文件信息 String
 34 		 * name=props.getProperty("uesrname");
 35 		 */
 36 		Properties props = new Properties();
 37 		try {
 38 			// 将src /db.propreties以InputStream方式载入
 39 			InputStream inStream = PropertiesConfig.class
 40 					.getResourceAsStream(fileName);
 41 			props.load(inStream);
 42 
 43 		} catch (Exception e) {
 44 			e.printStackTrace();
 45 		}
 46 		return props;
 47 	}
 48 
 49 
 50 	public static void main(String[] args) {
 51 		Properties properties = new Properties();
 52 		properties = getProperties("/dabase.properties");
 53 		System.out.println(properties);
 54 	}
 55 }
 56 

PropertyReadUtil.java

  1 package com.jacezhu.framework.utils.BeanUtil.pathUtil;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.FileInputStream;
  5 import java.io.InputStream;
  6 import java.util.Iterator;
  7 import java.util.Properties;
  8 
  9 /**
 10  * 主题: *.properties 配置文件内容读取工具
 11  * @author 刘军/shell_liu
 12  * 2015-9-8
 13  */
 14 
 15 public class PropertyReadUtil {
 16 	 //获取项目根文件路径地址
 17 	static String path = Thread.currentThread().getContextClassLoader() .getResource("").getPath();
 18 	/**
 19 	 *
 20 	 * @param propertiesName  需要被读取的配置文件
 21 	 * @return   Properties对象
 22 	 * @描述   :*.properties 配置文件内容读取  方法
 23 	 * @author 刘军/shell_liu
 24 	 * @创建日期 2015-9-8
 25 	 * @创建时间 下午5:31:05
 26 	 *
 27 	 */
 28 	 public static Properties getProperties(String propertiesName){
 29 		 Properties prop = new Properties();
 30 		 InputStream in;
 31 		try {
 32 			in = new BufferedInputStream (new FileInputStream(path+propertiesName));
 33 			prop.load(in); ///加载属性列表
 34 		}  catch(Exception e){
 35             System.out.println(e);
 36         }
 37 
 38 		return prop;
 39 
 40 
 41 	 }
 42 
 43 
 44 	public static void main(String[] args) {
 45         Properties prop = new Properties();
 46         prop=getProperties("database.properties");
 47         Iterator<String> it=prop.stringPropertyNames().iterator();
 48         while(it.hasNext()){
 49             String key=it.next();
 50             System.out.println(key+":"+prop.getProperty(key));
 51         }
 52 
 53 
 54     }
 55 }
 56 

四:JDBC 获取连接的封装

阿里巴巴开源的数据库连接jar 连接工具类 :DruidDataSourceUtil.java

  1 package com.jacezhu.framework.connectUtil;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.util.Properties;
  9 
 10 import javax.sql.DataSource;
 11 
 12 import com.alibaba.druid.pool.DruidDataSourceFactory;
 13 
 14 /**
 15  * The Class DruidDataSource.
 16  */
 17 public class DruidDataSourceUtil {
 18 
 19     /** 使用配置文件构建Druid数据源. */
 20     public static final int DRUID_MYSQL_SOURCE = 0;
 21 
 22     /** 使用配置文件构建Druid数据源. */
 23     public static final int DRUID_MYSQL_SOURCE2 = 1;
 24 
 25     /** 使用配置文件构建Dbcp数据源. */
 26     public static final int DBCP_SOURCE = 4;
 27     public static String confile = "jdbc.properties";
 28     public static Properties p = null;
 29 
 30     static {
 31         p = new Properties();
 32         InputStream inputStream = null;
 33         try {
 34             //java应用  
 35             confile = DruidDataSourceUtil.class.getClassLoader().getResource("").getPath()+ confile;
 36             System.out.println(confile);
 37             File file = new File(confile);
 38             inputStream = new BufferedInputStream(new FileInputStream(file));
 39             p.load(inputStream);
 40         } catch (Exception e) {
 41             e.printStackTrace();
 42         } finally {
 43             try {
 44                 if (inputStream != null) {
 45                     inputStream.close();
 46                 }
 47             } catch (IOException e) {
 48                 e.printStackTrace();
 49             }
 50         }
 51     }
 52 
 53     /**
 54      * 根据类型获取数据源
 55      *
 56      * @param sourceType
 57      *            数据源类型
 58      * @return druid或者dbcp数据源
 59      * @throws Exception
 60      *             the exception
 61      */
 62     public static final DataSource getDataSource(int sourceType) throws Exception {
 63         DataSource dataSource = null;
 64         switch (sourceType) {
 65         case DRUID_MYSQL_SOURCE:
 66             dataSource = DruidDataSourceFactory.createDataSource(p);
 67             break;
 68         case DRUID_MYSQL_SOURCE2:
 69             dataSource = DruidDataSourceFactory.createDataSource(p);
 70             break;
 71         case DBCP_SOURCE:
 72             // dataSource = BasicDataSourceFactory.createDataSource(  
 73             // MySqlConfigProperty.getInstance().getProperties());  
 74             break;
 75         }
 76         return dataSource;
 77     }
 78 	public static void main(String[] args) throws Exception {
 79 		int dbType=0;
 80 		DataSource dataSource=DruidDataSourceUtil.getDataSource(dbType);
 81 
 82 	}
 83 }
 84 

c3p0连接池管理类  DataSourceConnUtil.java

  1 package com.jacezhu.framework.connectUtil;
  2 
  3 import java.sql.Connection;
  4 import java.sql.SQLException;
  5 import java.util.Properties;
  6 
  7 import javax.sql.DataSource;
  8 
  9 import com.mchange.v2.c3p0.DataSources;
 10 
 11 /**
 12  *
 13 *      14 * 项目名称:s4h4s2s     15 * 类名称:DataSourceConnUtil     16 * 类描述: c3p0连接池管理类    17 * 创建人:刘军/jun liu     18 * 创建时间:2015-12-19 下午11:40:35     19 * 修改人:刘军/shall_liu     20 * 修改时间:2015-12-19 下午11:40:35     21 * 修改备注:     22 * @version      23 *      24  */
 25 public class DataSourceConnUtil {
 26 
 27 	private static final String JDBC_DRIVER = "driverClass";
 28 	private static final String JDBC_URL = "jdbcUrl";
 29 
 30 	private static DataSource ds;
 31 	/**
 32 	 * 初始化连接池代码块
 33 	 */
 34 	static{
 35 		initDBSource();
 36 	}
 37 
 38 	/**
 39 	 * 初始化c3p0连接池
 40 	 */
 41 	private static final void initDBSource(){
 42 		Properties c3p0Pro = new Properties();
 43 		try {
 44 			//加载配置文件
 45 			c3p0Pro.load(DataSourceConnUtil.class.getResourceAsStream("/config.properties"));
 46 			//c3p0Pro.load(new FileInputStream(PathUtil.getPath("dabase.properties")));
 47 		} catch (Exception e) {
 48 			e.printStackTrace();
 49 		}
 50 
 51 		String drverClass = c3p0Pro.getProperty(JDBC_DRIVER);
 52 		if(drverClass != null){
 53 			try {
 54 				//加载驱动类
 55 				Class.forName(drverClass);
 56 			} catch (ClassNotFoundException e) {
 57 				e.printStackTrace();
 58 			}
 59 
 60 		}
 61 
 62 		Properties jdbcpropes = new Properties();
 63 		Properties c3propes = new Properties();
 64 		for(Object key:c3p0Pro.keySet()){
 65 			String skey = (String)key;
 66 			if(skey.startsWith("c3p0.")){
 67 				c3propes.put(skey, c3p0Pro.getProperty(skey));
 68 			}else{
 69 				jdbcpropes.put(skey, c3p0Pro.getProperty(skey));
 70 			}
 71 		}
 72 
 73 		try {
 74 			//建立连接池
 75 			DataSource unPooled = DataSources.unpooledDataSource(c3p0Pro.getProperty(JDBC_URL),jdbcpropes);
 76 			ds = DataSources.pooledDataSource(unPooled,c3propes);
 77 
 78 		} catch (SQLException e) {
 79 			e.printStackTrace();
 80 		}
 81 	}
 82 
 83 	/**
 84 	 * 获取数据库连接对象
 85 	 * @return 数据连接对象
 86 	 * @throws SQLException
 87 	 */
 88 	public static synchronized Connection getConnection() {
 89 		  Connection conn = null;
 90 		  try {
 91 			conn = ds.getConnection();
 92 			conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
 93 			conn.setAutoCommit(false);//取消 事务管理:事务提交机制
 94 		} catch (SQLException e) {
 95 			e.printStackTrace();
 96 		}
 97 		  return conn;
 98 	}
 99 }
100 

普通的 数据库连接  ConnUtil.java

  1 package com.jacezhu.framework.connectUtil;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DriverManager;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 import java.sql.SQLException;
  8 import java.util.Properties;
  9 
 10 import javax.servlet.ServletException;
 11 
 12 
 13 /**
 14  *
 15 *      16 * 项目名称:s4h4s2s     17 * 类名称:ConnUtil     18 * 类描述:  主题:数据库连接工具类——包含取得连接和关闭资源; 没有数据库连接池     19 * 创建人:刘军/jun liu     20 * 创建时间:2015-12-19 下午11:40:21     21 * 修改人:刘军/shall_liu     22 * 修改时间:2015-12-19 下午11:40:21     23 * 修改备注:     24 * @version      25 *      26  */
 27 public class ConnUtil {
 28 	private static Connection conn = null;
 29 	private static String DRIVER_NAME;
 30 	private static String URL;
 31 	private static String USER_NAME;
 32 	private static String PASSWORD;
 33 
 34 
 35 	static {
 36 		try {
 37 			getConn();
 38 		} catch (Exception e) {
 39 			e.printStackTrace();
 40 		}
 41 	}
 42 
 43 	/**
 44 	 * 得到连接(没有入参)
 45 	 *
 46 	 * @return
 47 	 */
 48 	public static Connection getConn() {
 49 		try {
 50 			if (conn == null || conn.isValid(10) == false) {
 51 				ConnUtil connInfo = getConnectInfo();
 52 				conn = getConn(connInfo);
 53 			}
 54 			return conn;
 55 		} catch (Exception e) {
 56 			e.printStackTrace();
 57 			return null;
 58 		}finally{
 59 
 60 			try {
 61 				conn.close();
 62 			} catch (SQLException e) {
 63 				e.printStackTrace();
 64 			}
 65 		}
 66 	}
 67 
 68 	/**
 69 	 * 获取:ConnUtil 数据库连接参数的值
 70 	 *
 71 	 * @return MerchatInfo 对象
 72 	 * @描述 :从 dabase.properties配置文件获取 value 的值赋值给Properties 对象
 73 	 * @author 刘军/shell_liu
 74 	 * @创建日期 2015-9-8
 75 	 * @创建时间 下午9:04:32
 76 	 *
 77 	 */
 78 	public static ConnUtil getConnectInfo() {
 79 		ConnUtil connInfo = new ConnUtil();
 80 		try {
 81 			Properties  properties=new Properties();
 82 			//获取 配置文件的key-value
 83  	     	properties.load(ConnUtil.class.getResourceAsStream("/config.properties"));
 84 			//properties = PathUtil.returnPropertiesValue("dabase.properties");
 85 
 86 			ConnUtil.setDRIVER_NAME(properties.getProperty("driverClass"));
 87 			ConnUtil.setURL(properties.getProperty("jdbcUrl"));
 88 			ConnUtil.setUSER_NAME(properties.getProperty("user"));
 89 			ConnUtil.setPASSWORD(properties.getProperty("password"));
 90 			return connInfo;
 91 		} catch (Exception e) {
 92 			  try {
 93 					throw new ServletException("加载数据库链接参数失败");
 94 
 95 				} catch (ServletException e1) {
 96 					e1.printStackTrace();
 97 					return null;
 98 				}
 99 		}
100 	}
101 
102 	/**
103 	 * 得到连接
104 	 *
105 	 * @param connUtil
106 	 *            (数据库连接需要的值)
107 	 * @return
108 	 */
109 	@SuppressWarnings("static-access")
110 	public static Connection getConn(ConnUtil connUtil) {
111 		try {
112 			Class.forName(connUtil.getDRIVER_NAME());
113 			conn = DriverManager.getConnection(connUtil.getURL(),
114 					connUtil.getUSER_NAME(), connUtil.getPASSWORD());
115 			conn.setAutoCommit(false);//取消 事务管理:事务提交机制
116 		} catch (Exception e) {
117 			  try {
118 				throw new ServletException("链接数据库失败!");
119 			} catch (ServletException e1) {
120 				e1.printStackTrace();
121 			}
122 		}
123 		return conn;
124 	}
125 
126 	/**
127 	 * 关闭连接
128 	 *
129 	 * @param conn
130 	 * @throws SQLException
131 	 */
132 	public static void close(Connection conn) throws SQLException {
133 		if (conn != null) {
134 			conn.close();
135 			conn = null;
136 		}
137 	}
138 
139 	/**
140 	 * 关闭PreparedStatement
141 	 *
142 	 * @param pstmt
143 	 * @throws SQLException
144 	 */
145 	public static void close(PreparedStatement pstmt) throws SQLException {
146 		if (pstmt != null) {
147 			pstmt.close();
148 			pstmt = null;
149 		}
150 	}
151 
152 	/**
153 	 * 关闭结果集
154 	 *
155 	 * @param rs
156 	 * @throws SQLException
157 	 */
158 	public static void close(ResultSet rs) throws SQLException {
159 		if (rs != null) {
160 			rs.close();
161 			rs = null;
162 		}
163 	}
164 
165 
166 	//----------------------get set-------------------------------------------------
167 	/**
168 	 *
169 	* @Title: getDRIVER_NAME  170 	* @Description: ()  171 	* @param @return    设定文件  172 	* @return String    返回类型  173 	* @throws  174 	 */
175 	public static String getDRIVER_NAME() {
176 		return DRIVER_NAME;
177 	}
178 
179 	public static void setDRIVER_NAME(String dRIVER_NAME) {
180 		DRIVER_NAME = dRIVER_NAME;
181 	}
182 
183 	public static String getURL() {
184 		return URL;
185 	}
186 
187 	public static void setURL(String uRL) {
188 		URL = uRL;
189 	}
190 
191 	public static String getUSER_NAME() {
192 		return USER_NAME;
193 	}
194 
195 	public static void setUSER_NAME(String uSER_NAME) {
196 		USER_NAME = uSER_NAME;
197 	}
198 
199 	public static String getPASSWORD() {
200 		return PASSWORD;
201 	}
202 
203 	public static void setPASSWORD(String pASSWORD) {
204 		PASSWORD = pASSWORD;
205 	}
206    //--------------------main 方法----------------------------------------------
207 	/**
208 	 * 测试 连接是否成功
209 	 *
210 	 * @param args
211 	 */
212 	public static void main(String[] args) {
213 		getConn();
214 	}
215 }

SqlParameter.java

  1 package com.jacezhu.framework.connectUtil.jdbcUtl;
  2 /**
  3  *
  4 * @Title: SqlParameter.java    5 * @Package com.jacezhu.framework.connectUtil.jdbcUtl    6 * @Description: (存储过程参数类型)    7 * @author  刘军
  8 * @date 2016-3-19 下午2:47:02    9 * @version V1.0    10  */
 11 public class SqlParameter {
 12 
 13 	/**
 14      * 参数名称
 15      */
 16     public String Name;
 17     /**
 18      * 参数值
 19      */
 20     public Object Value;
 21     /**
 22      * true表示参数为输出类型
 23      */
 24     public boolean OutPut;
 25     /**
 26      * 参数类型
 27      */
 28     public int Type;
 29     /**
 30      * 输入类型参数的构造函数
 31      * @param name 存储过程 输入类型 参数名称
 32      * @param value 存储过程 输入类型 参数值
 33      */
 34     public SqlParameter(String name,Object value){
 35         this.Name = name;
 36         this.Value= value;
 37     }
 38     /**
 39      * 输出类型参数的构造函数
 40      * @param type 存储过程 输出类型 参数类型
 41      * @param name 存储过程 输出类型 参数名称
 42      */
 43     public SqlParameter(int type,String name){
 44         this.Name = name;
 45         this.OutPut = true;
 46         this.Type = type;
 47     }
 48     /**
 49      * 返回类型参数的构造函数
 50      * @param type 存储过程 返回类型
 51      */
 52     public SqlParameter(int type){
 53         this.Name = "";
 54         this.OutPut = true;
 55         this.Type = type;
 56     }
 57 }
 58 

PageModel.java

  1 package com.jacezhu.framework.connectUtil.jdbcUtl;
  2 import java.util.List;
  3 /**
  4  * 分页封装类
  5 *       6 * 项目名称:s4h4s2s      7 * 类名称:PageModel      8 * 类描述:      9 * 创建人:刘军/jun liu     10 * 创建时间:2015-12-20 下午2:40:55     11 * 修改人:Administrator     12 * 修改时间:2015-12-20 下午2:40:55     13 * 修改备注:     14 * @version      15 *      16  */
 17 public class PageModel<T> {
 18 
 19 	//结果集
 20 	private List<T> list;
 21 
 22 	//记录数
 23 	private int totalRecords;
 24 
 25 	//每页多少条数据
 26 	private int pageSize;
 27 
 28 	//第几页
 29 	private int pageNo;
 30 	//总共多少页
 31 	private int countPageNo;
 32 
 33 	/**
 34 	 * 返回总页数
 35 	 * @return
 36 	 */
 37 	public int getTotalPages() {
 38 		return (totalRecords + pageSize - 1) / pageSize;
 39 	}
 40 
 41 	/**
 42 	 * 首页
 43 	 * @return
 44 	 */
 45 	public int getTopPageNo() {
 46 		return 1;
 47 	}
 48 
 49 	/**
 50 	 * 上一页
 51 	 * @return
 52 	 */
 53 	public int getPreviousPageNo() {
 54 		if (this.pageNo <= 1) {
 55 			return 1;
 56 		}
 57 		return this.pageNo - 1;
 58 	}
 59 
 60 	/**
 61 	 * 下一页
 62 	 * @return
 63 	 */
 64 	public int getNextPageNo() {
 65 		if (this.pageNo >= getButtomPageNo()) {
 66 			return getButtomPageNo();
 67 		}
 68 		return this.pageNo + 1;
 69 	}
 70 
 71 	/**
 72 	 * 尾页
 73 	 * @return
 74 	 */
 75 	public int getButtomPageNo() {
 76 		return getTotalPages();
 77 	}
 78 
 79 	public List<T> getList() {
 80 		return list;
 81 	}
 82 
 83 	public void setList(List<T> list) {
 84 		this.list = list;
 85 	}
 86 
 87 	public int getTotalRecords() {
 88 		return totalRecords;
 89 	}
 90 
 91 	public void setTotalRecords(int totalRecords) {
 92 		this.totalRecords = totalRecords;
 93 	}
 94 
 95 	public int getPageSize() {
 96 		return pageSize;
 97 	}
 98 
 99 	public void setPageSize(int pageSize) {
100 		this.pageSize = pageSize;
101 	}
102 
103 	public int getPageNo() {
104 		return pageNo;
105 	}
106 
107 	public void setPageNo(int pageNo) {
108 		this.pageNo = pageNo;
109 	}
110 
111 	public int getCountPageNo() {
112 		return countPageNo;
113 	}
114 
115 	public void setCountPageNo(int countPageNo) {
116 		this.countPageNo = countPageNo;
117 	}
118 
119 }
120 

ObjectMapper.java

  1 package com.jacezhu.framework.connectUtil.jdbcUtl;
  2 
  3 import java.sql.ResultSet;
  4 /**
  5  *
  6 * @Title: ObjectMapper.java    7 * @Package com.jacezhu.framework.connectUtil.jdbcUtl    8 * @Description: (用于转换数据结果集 )    9 * @author  刘军
 10 * @date 2016-3-19 上午9:52:18   11 * @version V1.0    12  */
 13 public interface ObjectMapper {
 14 	public Object mapping(ResultSet rs);
 15 
 16 }

五:JDBC 封装层:dao层

BaseDaoI.java

  1 package com.jacezhu.dao;
  2 
  3 import java.io.Serializable;
  4 import java.math.BigInteger;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 public interface BaseDaoI<T> {
  9 
 10 	public Serializable save(T o);
 11 
 12 	public void delete(T o);
 13 
 14 	public void update(T o);
 15 
 16 	public void saveOrUpdate(T o);
 17 
 18 	public T get(Class<T> c, Serializable id);
 19 
 20 	public T get(String hql);
 21 
 22 	public T get(String hql, Map<String, Object> params);
 23 
 24 	public List<T> find(String hql);
 25 
 26 	public List<T> find(String hql, Map<String, Object> params);
 27 
 28 	public List<T> find(String hql, int page, int rows);
 29 
 30 	public List<T> find(String hql, Map<String, Object> params, int page,
 31 			int rows);
 32 
 33 	public Long count(String hql);
 34 
 35 	public Long count(String hql, Map<String, Object> params);
 36 
 37 	public int executeHql(String hql);
 38 
 39 	public int executeHql(String hql, Map<String, Object> params);
 40 
 41 	public List<Object[]> findBySql(String sql);
 42 
 43 	public List<Object[]> findBySql(String sql, int page, int rows);
 44 
 45 	public List<Object[]> findBySql(String sql, Map<String, Object> params);
 46 
 47 	public List<Object[]> findBySql(String sql, Map<String, Object> params,
 48 			int page, int rows);
 49 
 50 	public int executeSql(String sql);
 51 
 52 	public int executeSql(String sql, Map<String, Object> params);
 53 
 54 	public BigInteger countBySql(String sql);
 55 
 56 	public BigInteger countBySql(String sql, Map<String, Object> params);
 57 
 58 	public void refresh(T o);
 59 
 60 	public void merge(T o);
 61 }
 62 

JdbcBaseDao.java

  1 package com.jacezhu.dao;
  2 
  3 import java.sql.Connection;
  4 import java.sql.PreparedStatement;
  5 import java.sql.ResultSet;
  6 import java.sql.SQLException;
  7 import java.lang.reflect.Field;
  8 import java.sql.Statement;
  9 import java.sql.CallableStatement;
 10 import java.sql.ResultSetMetaData;
 11 import java.util.ArrayList;
 12 import java.util.HashMap;
 13 import java.util.List;
 14 import java.util.Map;
 15 import java.sql.*;
 16 import java.lang.reflect.*;
 17 
 18 
 19 import com.jacezhu.framework.connectUtil.ConnUtil;
 20 import com.jacezhu.framework.connectUtil.DataSourceConnUtil;
 21 import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
 22 import com.jacezhu.framework.connectUtil.jdbcUtl.SqlParameter;
 23 
 24 
 25 public interface JdbcBaseDao {
 26 
 27     /**
 28      *
 29     * @author  刘军
 30     * @date 2016-3-19 上午11:14:17   31     * @version V1.0    32     * @Title: getStatement   33     * @Description: ( )   34     * @param @return
 35     * @param @throws SQLException    设定文件   36     * @return Connection    返回类型   37     * @throws   38      */
 39 	public Connection getStatement() throws SQLException;
 40 
 41 	/**
 42 	 *
 43 	 * @Title: update   44 	 * @Description: (更新:update)   45 	 * @param @param sql
 46 	 * @param @param obj
 47 	 * @param @param isGenerateKey
 48 	 * @param @return    设定文件   49 	 * @return boolean    返回类型   50 	 * @throws   51 	 */
 52 	public boolean update(String sql, Object[] obj, boolean isGenerateKey) ;
 53 	/**
 54 	 *
 55 	 * @Title: updateByPreparedStatement  增加、删除、改
 56 	 * @Description: (增加、删除、改)   57 	 * @param @param sql
 58 	 * @param @param params
 59 	 * @param @return    设定文件   60 	 * @return boolean    返回类型   61 	 * @throws   62 	 */
 63 	public boolean updateByPreparedStatement(String sql, List<Object> params) ;
 64 
 65 
 66 
 67 	/**
 68 	 * insert update delete SQL语句的执行的统一方法
 69 	 *
 70 	 * @param sql
 71 	 *            SQL语句
 72 	 * @param params
 73 	 *            参数数组,若没有参数则为null
 74 	 * @return 受影响的行数
 75 	 */
 76 	public int executeUpdate(String sql, Object[] params) ;
 77 
 78 
 79 	/**
 80 	 *
 81 	 * @Title: query   82 	 * @Description: ( )   83 	 * @param @param sql
 84 	 * @param @param obj
 85 	 * @param @param mapper
 86 	 * @param @return    设定文件   87 	 * @return List<? extends Object>    返回类型   88 	 * @throws   89 	 */
 90 	public List<? extends Object> query(String sql, Object[] obj,
 91 			ObjectMapper mapper) ;
 92 
 93 	/**
 94 	 *
 95 	* @author   liujun<1136808529@qq.coom>
 96 	* @date 2016-5-12 下午1:58:12   97 	* @version V1.0    98 	* @Title: query   99 	* @Description: (
100 	 *
101 	 *)  102 	* @param @param sql
103 	* @param @param obj
104 	* @param @param mapper
105 	* @param @return    设定文件  106 	* @return List<? extends Object>    返回类型  107 	* @throws  108 	 */
109 	public List<? extends Object> query(String sql, List obj,
110 			ObjectMapper mapper) ;
111 
112 
113 
114 
115      /**
116       *
117      * @Title: returnTableCount  118      * @Description: ( select count(*)from table 的总数据条数)  119      * @param @param table
120      * @param @return    设定文件  121      * @return int    返回类型  122      * @throws  123       */
124 	public int returnTableCount(String table);
125 	/**
126 	 *
127 	* @author   liujun<1136808529@qq.coom>
128 	* @date 2016-5-12 下午11:19:59  129 	* @version V1.0   130 	* @Title: Count  131 	* @Description: (
132 	 * 返回 统计count 数据的数量
133 	 *)  134 	* @param @param sql
135 	* @param @return    设定文件  136 	* @return int    返回类型  137 	* @throws  138 	 */
139 	public long  Count(String sql);
140 	/**
141 	 *
142 	 * @Title: findSimpleResult  获取最后一条(单条)记录
143 	 * @Description: (查询单条记录)  144 	 * @param @param sql
145 	 * @param @param params
146 	 * @param @return    设定文件  147 	 * @return Map<String,Object>    返回类型  148 	 * @throws  149 	 */
150 	public Map<String, Object> findSimpleResult(String sql, List<Object> params);
151 	/**
152 	 * 获取结果集,并将结果放在List中
153 	 *
154 	 * @param sql
155 	 *            SQL语句
156 	 * @return List 结果集
157 	 */
158 	public List<Object> excuteQuery(String sql, Object[] params) ;
159 
160      /**
161 	 *
162 	 * @Title: findModeResult  查询多条记录
163 	 * @Description: (查询多条记录)  164 	 * @param @param sql
165 	 * @param @param params
166 	 * @param @return
167 	 * @param @throws SQLException    设定文件  168 	 * @return List<Map<String,Object>>    返回类型  169 	 * @throws  170 	 */
171 	public List<Map<String, Object>> findModeResult(String sql,	List<Object> params) ;
172 
173 	/**
174 	 * SQL 查询将查询结果:一行一列
175 	 *
176 	 * @param sql
177 	 *            SQL语句
178 	 * @param params
179 	 *            参数数组,若没有参数则为null
180 	 * @return 结果集
181 	 */
182 	public Object executeQuerySingle(String sql, Object[] params) ;
183 
184 
185 	/**
186 	 *
187 	 * @Title: findSimpleRefResult  通过反射机制查询单条记录
188 	 * @Description: (通过反射机制查询单条记录)  189 	 * @param @param sql
190 	 * @param @param params
191 	 * @param @param cls
192 	 * @param @return
193 	 * @param @throws Exception    设定文件  194 	 * @return T    返回类型  195 	 * @throws  196 	 */
197 	public    <T> T  findSimpleRefResult(String sql, List<Object> params,Class<T> cls) ;
198 	/**
199 	 * 通过反射机制查询多条记录
200 	 *
201 	 * @param sql
202 	 * @param params
203 	 * @param cls
204 	 * @return
205 	 * @throws Exception
206 	 */
207 	public <T> List<T> findMoreRefResult(String sql, List<Object> params,
208 			Class<T> cls) ;
209 
210 	/**
211 	 *
212 	 * @Title: find  213 	 * @Description: ( 查询一条记录)  214 	 * @param @param sql
215 	 * @param @param obj
216 	 * @param @param mapper
217 	 * @param @return    设定文件  218 	 * @return Object    返回类型  219 	 * @throws  220 	 */
221 	public Object find(String sql, Object[] obj, ObjectMapper mapper)  ;
222 	/**
223 	 *
224 	* @author   liujun<1136808529@qq.coom>
225 	* @date 2016-5-14 下午1:18:51  226 	* @version V1.0   227 	* @Title: find  228 	* @Description: (
229 	 *  查询一条记录
230 	 *)  231 	* @param @param sql
232 	* @param @param obj
233 	* @param @param mapper
234 	* @param @return    设定文件  235 	* @return Object    返回类型  236 	* @throws  237 	 */
238 	public Object find(String sql, List obj, ObjectMapper mapper);
239 	/**
240 	 *
241 	 * @Title: executeQuery  统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源
242 	 * @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源)  243 	 * @param @param sql
244 	 * @param @param parameters
245 	 * @param @return    设定文件  246 	 * @return ArrayList    返回类型  247 	 * @throws  248 	 */
249 	@SuppressWarnings({ "rawtypes", "unchecked" })
250 	public ArrayList executeQuery(String sql, String[] parameters);
251 
252 	/**
253 	 *
254 	 * @Title: executeQuery  by statement
255 	 * @Description: (执行 查询sql 获取结果集)  256 	 * @param @param sql
257 	 * @param @return statement resultSet
258 	 * @param @throws SQLException    设定文件  259 	 * @return ResultSet    返回类型  260 	 * @throws  261 	 */
262 	public ResultSet executeQuery(String sql);
263 
264 
265 	//-------------------------------------------对象化---------------
266 
267 
268 
269 
270 
271 
272 
273 
274 //----------------------存储过程调用-------------------------------------------
275 
276 
277 	/**
278 	 * 存储过程带有一个输出参数的方法
279 	 *
280 	 * @param sql
281 	 *            存储过程语句
282 	 * @param params
283 	 *            参数数组
284 	 * @param outParamPos
285 	 *            输出参数位置
286 	 * @param SqlType
287 	 *            输出参数类型
288 	 * @return 输出参数的值
289 	 */
290 	public Object executeQuery(String sql, Object[] params, int outParamPos,
291 			int SqlType) ;
292 
293     /**
294      * 执行不返回结果集的存储过程
295      *
296      * @param sql
297      *            存储过程名称
298      * @param params
299      *            存储过程参数
300      * @throws ClassNotFoundException
301      * @throws SQLException
302      */
303     public   void executeNonQuery(String sql, SqlParameter... params) ;
304 
305     /**
306      * 执行Insert语句,返回Insert成功之后标识列的值
307      *
308      * @param sql
309      * @return
310      * @throws ClassNotFoundException
311      * @throws SQLException
312      */
313     public   int executeIdentity(String sql) ;
314     /**
315      * 执行不返回结果集的存储过程
316      *
317      * @param sql
318      *            存储过程名称
319      * @param params
320      *            存储过程参数
321      * @throws ClassNotFoundException
322      * @throws SQLException
323      */
324     public   void executeNonQuery1(String sql, SqlParameter... params) ;
325     /**
326      * 执行返回聚合函数的操作
327      *
328      * @param sql
329      *            含有聚合函数的SQL语句
330      * @return 聚合函数的执行结果
331      * @throws SQLException
332      * @throws ClassNotFoundException
333      */
334     public   int executeScalar(String sql) ;
335     /**
336      * 执行返回泛型集合的SQL语句
337      *
338      * @param cls
339      *            泛型类型
340      * @param sql
341      *            查询SQL语句
342      * @return 泛型集合
343      * @throws ClassNotFoundException
344      * @throws SQLException
345      * @throws InstantiationException
346      * @throws IllegalAccessException
347      */
348     public   <T> List<T> executeList(Class<T> cls, String sql) ;
349     /**
350      * 执行返回泛型集合的存储过程
351      *
352      * @param cls
353      *            泛型类型
354      * @param sql
355      *            存储过程名称
356      * @param params
357      *            存储过程参数
358      * @return 泛型集合
359      * @throws ClassNotFoundException
360      * @throws SQLException
361      * @throws InstantiationException
362      * @throws IllegalAccessException
363      */
364     public   <T> List<T> executeList(Class<T> cls, String sql,
365             SqlParameter... params)  ;
366     /**
367      * 执行返回泛型类型对象的SQL语句
368      *
369      * @param cls
370      *            泛型类型
371      * @param sql
372      *            SQL语句
373      * @return 泛型类型对象
374      * @throws SQLException
375      * @throws ClassNotFoundException
376      * @throws InstantiationException
377      * @throws IllegalAccessException
378      */
379     public   <T> T executeEntity(Class<T> cls, String sql)  ;
380     /**
381      * 执行返回泛型类型对象的存储过程
382      *
383      * @param cls
384      *            泛型类型
385      * @param sql
386      *            SQL语句
387      * @param params
388      *            存储过程参数
389      * @return 泛型类型对象
390      * @throws SQLException
391      * @throws ClassNotFoundException
392      * @throws InstantiationException
393      * @throws IllegalAccessException
394      */
395     public   <T> T executeEntity(Class<T> cls, String sql,
396             SqlParameter... params) ;
397 
398 	/**
399 	 *
400 	 * @Title: executeUpdate  by statement
401 	 * @Description: (更新结果集)  402 	 * @param @param sql
403 	 * @param @return
404 	 * @param @throws SQLException    设定文件  405 	 * @return int    返回类型  406 	 * @throws  407 	 */
408 	@SuppressWarnings("null")
409 	public int executeUpdate(String sql)  ;
410 
411 
412 
413 
414 	/**
415 	 *
416 	* @author   liujun<1136808529@qq.coom>
417 	* @date 2016-5-17 上午11:33:28  418 	* @version V1.0   419 	* @Title: getSeq  420 	* @Description:  (
421 	 *  获取sequence 序列号
422 	 *)  423 	* @param @param sequenceName
424 	* @param @return    设定文件  425 	* @return int    返回类型  426 	* @throws  427 	 */
428 	public int getSeq(String sequenceName) ;
429 }
430 

jdbc.java

  1 package com.jacezhu.dao;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 import java.util.Map;
  6 
  7 import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
  8 import com.jacezhu.framework.connectUtil.jdbcUtl.PageModel;
  9 
 10 /**
 11  *
 12 * @Title: JdbcUtil.java   13 * @Package com.jacezhu.framework.connectUtil.jdbcUtl   14 * @Description: (JdbcUtil)   15 * @author  刘军
 16 * @date 2016-3-17 下午11:04:19   17 * @version V1.0    18  */
 19 public interface JdbcDao  {
 20 
 21 
 22 	/**
 23 	 *
 24 	* @Title: insert   25 	* @Description: (插入单挑数据)   26 	* @param @param sql 查询sql
 27 	* @param @param obj 参数数组
 28 	* @param @param isGenerateKey (true  false)
 29 	* @param @return    设定文件   30 	* @return boolean    返回类型   31 	* @throws   32 	 */
 33 	public boolean insert(String sql, Object[] obj);
 34 	/**
 35 	 *
 36 	* @author  刘军
 37 	* @date 2016-3-19 下午2:23:42   38 	* @version V1.0    39 	* @Title: insertLines   40 	* @Description: (新增)   41 	* @param @param sql
 42 	* @param @param obj
 43 	* @param @return    设定文件   44 	* @return int    返回类型   45 	* @throws   46 	 */
 47 	public int insertLines(String sql, Object[] obj);
 48 	/**
 49 	 *
 50 	* @author  刘军
 51 	* @date 2016-3-19 下午2:05:19   52 	* @version V1.0    53 	* @Title: insert   54 	* @Description: (新增)   55 	* @param @param sql
 56 	* @param @param obj
 57 	* @param @return    设定文件   58 	* @return boolean    返回类型   59 	* @throws   60 	 */
 61 	public boolean insertByList(String sql, List<Object> obj);
 62 
 63 	/**
 64 	 *
 65 	* @Title: delete   66 	* @Description: (删除单挑数据)   67 	* @param @param sql 删除sql
 68 	* @param @param obj 参数数组
 69 	* @param @param isGenerateKey (true  false)
 70 	* @param @return    设定文件   71 	* @return boolean    返回类型   72 	* @throws   73 	 */
 74 	public boolean delete(String sql, Object[] obj);
 75 	/**
 76 	 *
 77 	* @author  刘军
 78 	* @date 2016-3-19 下午2:19:20   79 	* @version V1.0    80 	* @Title: delete   81 	* @Description: (删除单挑数据)   82 	* @param @param sql
 83 	* @param @param obj
 84 	* @param @return    设定文件   85 	* @return boolean    返回类型   86 	* @throws   87 	 */
 88 	public boolean delete(String sql,List<Object> obj);
 89 
 90 	 /**
 91 	  *
 92 	 * @Title: deleteALL   93 	 * @Description: (批量删除数据)   94 	 * @param @param sql
 95 	 * @param @param obj
 96 	 * @param @return    设定文件   97 	 * @return boolean    返回类型   98 	 * @throws   99 	  */
100 	public boolean deleteALL(String sql, Object[] obj);
101 	/**
102 	 *
103 	* @author  刘军
104 	* @date 2016-3-19 下午2:20:56  105 	* @version V1.0   106 	* @Title: deleteALL  107 	* @Description: (删除 批量删除 )  108 	* @param @param sql
109 	* @param @param obj
110 	* @param @return    设定文件  111 	* @return boolean    返回类型  112 	* @throws  113 	 */
114 	public boolean deleteALL(String sql,List<Object> obj);
115 	 /**
116 	  *
117 	 * @Title: update  118 	 * @Description: (更新单挑数据记录)  119 	 * @param @param sql
120 	 * @param @param obj
121 	 * @param @return    设定文件  122 	 * @return boolean    返回类型  123 	 * @throws  124 	  */
125 	public boolean update(String sql, Object[] obj);
126 	/**
127 	 *
128 	* @author  刘军
129 	* @date 2016-3-19 下午2:21:45  130 	* @version V1.0   131 	* @Title: update  132 	* @Description: (修改 )  133 	* @param @param sql
134 	* @param @param obj
135 	* @param @return    设定文件  136 	* @return boolean    返回类型  137 	* @throws  138 	 */
139 	public boolean update(String sql, List<Object> obj);
140 	 /**
141 	  *
142 	 * @Title: queryFrist  143 	 * @Description: (查询出第一条数据记录)  144 	 * @param @param tale
145 	 * @param @param objParams
146 	 * @param @return    设定文件  147 	 * @return Object    返回类型  148 	 * @throws  149 	  */
150 	 public Object queryFrist(String tale,Object[] objParams,ObjectMapper mapper);
151 	 /**
152 	  *
153 	 * @author  刘军
154 	 * @date 2016-3-19 上午9:41:06  155 	 * @version V1.0   156 	 * @Title: find  157 	 * @Description: (查询一条记录 )  158 	 * @param @param sql
159 	 * @param @param obj
160 	 * @param @param mapper
161 	 * @param @return    设定文件  162 	 * @return Object    返回类型  163 	 * @throws  164 	  */
165 	 public	 Object find(String sql, Object[] obj, ObjectMapper mapper);
166 	 /**
167 		 *
168 		* @author   liujun<1136808529@qq.coom>
169 		* @date 2016-5-14 下午1:18:51  170 		* @version V1.0   171 		* @Title: find  172 		* @Description: (
173 		 *  查询一条记录
174 		 *)  175 		* @param @param sql
176 		* @param @param obj
177 		* @param @param mapper
178 		* @param @return    设定文件  179 		* @return Object    返回类型  180 		* @throws  181 		 */
182 		public Object find(String sql, List obj, ObjectMapper mapper);
183 	/**
184 	 *
185 	* @Title: query  186 	* @Description: ( 查询所有的数据记录;并以list 集合(或者:Object 对象)返回 )  187 	* @param @param sql
188 	* @param @param obj
189 	* @param @param mapper
190 	* @param @return    设定文件  191 	* @return List<? extends Object>    返回类型  192 	* @throws  193 	 */
194 	public List<? extends Object> query(String sql, Object[] obj,
195 			ObjectMapper mapper) ;
196 	/**
197 	 *
198 	* @author   liujun<1136808529@qq.coom>
199 	* @date 2016-5-12 下午2:03:54  200 	* @version V1.0   201 	* @Title: query  202 	* @Description: (
203 	 *
204 	 *)  205 	* @param @param sql
206 	* @param @param obj
207 	* @param @param mapper
208 	* @param @return    设定文件  209 	* @return List<? extends Object>    返回类型  210 	* @throws  211 	 */
212 	public List<? extends Object> query(String sql, List obj,
213 			ObjectMapper mapper) ;
214 	/**
215 	 *
216 	* @author   liujun<1136808529@qq.coom>
217 	* @date 2016-5-12 下午11:19:59  218 	* @version V1.0   219 	* @Title: Count  220 	* @Description: (
221 	 * 返回 统计count 数据的数量
222 	 *)  223 	* @param @param sql
224 	* @param @return    设定文件  225 	* @return int    返回类型  226 	* @throws  227 	 */
228 	public long  Count(String sql);
229 	/**
230 	 *
231 	* @Title: CountNum  232 	* @Description: ( select count(*)from table 的总数据条数)
233 	* @param @param tableName (数据库表名)
234 	* @param @return    设定文件  235 	* @return int    返回类型  236 	* @throws  237 	 */
238 	public int CountNum (String tableName);
239 	/**
240 	 *
241 	* @Title: queryPageNumber  242 	* @Description: (分页查询)  243 	* @param @param pageNo 第几页
244 	* @param @param pageSize  一页显示多少条数据
245 	* @param @param table  查询哪个表
246 	* 全表无条件查询
247 	*  {select * from ( tablea a,tableb b where a.id=b.id)limt numStrat,numStop}
248 	* 全表 带条件模糊查询:
249 	*SELECT * FROM  demo a ,demo b WHERE a.id=b.id AND  a.id LIKE "1%" LIMIT 0,15;
250 	* @param @return    设定文件  251 	* @return PageModel    返回类型  252 	* @throws  253 	 */
254 	public PageModel queryPageNumber(int pageNo, int pageSize,String table) ;
255 	/**
256 	 *
257 	 * @Title: findSimpleResult  获取最后一条(单条)记录
258 	 * @Description: (查询单条记录)  259 	 * @param @param sql
260 	 * @param @param params
261 	 * @param @return    设定文件  262 	 * @return Map<String,Object>    返回类型  263 	 * @throws  264 	 */
265 	public Map<String, Object> findSimpleResult(String sql, List<Object> params);
266 	/**
267 	 *
268 	* @author  刘军
269 	* @date 2016-3-19 上午12:30:02  270 	* @version V1.0   271 	* @Title: findModeResult  查询多条记录
272 	* @Description: (查询多条记录)  273 	* @param @param sql
274 	* @param @param params
275 	* @param @return    设定文件  276 	* @return List<Map<String,Object>>    返回类型  277 	* @throws  278 	 */
279 	public List<Map<String, Object>> findModeResult(String sql,	List<Object> params);
280 	/**
281 	 *
282 	* @author  刘军
283 	* @date 2016-3-19 上午8:43:07  284 	* @version V1.0   285 	* @Title: executeQuerySingle  286 	* @Description: (SQL 查询将查询结果:一行一列)  287 	* @param @param sql
288 	* @param @param params
289 	* @param @return    设定文件  290 	* @return Object    返回类型  291 	* @throws  292 	 */
293 	public Object executeQuerySingle(String sql, Object[] params);
294 
295 	/**
296 	 *
297 	* @author  刘军
298 	* @date 2016-3-19 上午9:08:05  299 	* @version V1.0   300 	* @Title: findSimpleRefResult  301 	* @Description: (通过反射机制查询单条记录
302 	*   如果需要调用:请调用jdbcBaseUtil
303 	* )  304 	* @param @param sql
305 	* @param @param params
306 	* @param @param cls
307 	* @param @return    设定文件  308 	* @return T    返回类型  309 	* @throws  310 	 */
311 	public <T> T findSimpleRefResult(String sql, List<Object> params,Class<T> cls) ;
312 	/**
313 	 *
314 	* @author  刘军
315 	* @date 2016-3-19 上午9:13:39  316 	* @version V1.0   317 	* @Title: findMoreRefResult  318 	* @Description: ( 通过反射机制查询多条记录)  319 	* @param @param sql
320 	* @param @param params
321 	* @param @param cls
322 	* @param @return    设定文件  323 	* @return List<T>    返回类型  324 	* @throws  325 	 */
326 	public <T> List<T> findMoreRefResult(String sql, List<Object> params,
327 			Class<T> cls);
328 	/**
329 	 *
330 	* @author  刘军
331 	* @date 2016-3-19 上午11:03:06  332 	* @version V1.0   333 	* @Title: excuteQuery  334 	* @Description: (获取结果集,并将结果放在List中)  335 	* @param @param sql
336 	* @param @param params
337 	* @param @return    设定文件  338 	* @return List<Object>    返回类型  339 	* @throws  340 	 */
341 	public List<Object> excuteQuery(String sql, Object[] params);
342 	/**
343 	 *
344 	* @author  刘军
345 	* @date 2016-3-19 上午11:03:03  346 	* @version V1.0   347 	* @Title: executeQuery  348 	* @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,)  349 	* @param @param sql
350 	* @param @param parameters
351 	* @param @return    设定文件  352 	* @return ArrayList    返回类型  353 	* @throws  354 	 */
355 	public ArrayList executeQuery(String sql, String[] parameters) ;
356 
357 	/**
358 	 *
359 	* @author   liujun<1136808529@qq.coom>
360 	* @date 2016-5-17 上午11:33:28  361 	* @version V1.0   362 	* @Title: getSeq  363 	* @Description:  (
364 	 *  获取sequence 序列号
365 	 *)  366 	* @param @param sequenceName
367 	* @param @return    设定文件  368 	* @return int    返回类型  369 	* @throws  370 	 */
371 	public int getSeq(String sequenceName);
372 }
373 

BaseDaoImpl.java

  1 package com.jacezhu.dao.impl;
  2 
  3 import java.io.Serializable;
  4 import java.math.BigInteger;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import com.jacezhu.dao.BaseDaoI;
  9 
 10 import org.hibernate.Query;
 11 import org.hibernate.SQLQuery;
 12 import org.hibernate.Session;
 13 import org.hibernate.SessionFactory;
 14 import org.springframework.beans.factory.annotation.Autowired;
 15 import org.springframework.stereotype.Repository;
 16 
 17 @Repository
 18 public class BaseDaoImpl<T> implements BaseDaoI<T> {
 19 
 20 	@Autowired
 21 	private SessionFactory sessionFactory;
 22 
 23 	/**
 24 	 * 获得当前事物的session
 25 	 *
 26 	 * @return org.hibernate.Session
 27 	 */
 28 	public Session getCurrentSession() {
 29 		return this.sessionFactory.getCurrentSession();
 30 	}
 31 
 32 	@Override
 33 	public Serializable save(T o) {
 34 		if (o != null) {
 35 			return this.getCurrentSession().save(o);
 36 		}
 37 		return null;
 38 	}
 39 
 40 	@Override
 41 	public T get(Class<T> c, Serializable id) {
 42 		return (T) this.getCurrentSession().get(c, id);
 43 	}
 44 
 45 	@Override
 46 	public T get(String hql) {
 47 		Query q = this.getCurrentSession().createQuery(hql);
 48 		List<T> l = q.list();
 49 		if ((l != null) && (l.size() > 0)) {
 50 			return l.get(0);
 51 		}
 52 		return null;
 53 	}
 54 
 55 	@Override
 56 	public T get(String hql, Map<String, Object> params) {
 57 		Query q = this.getCurrentSession().createQuery(hql);
 58 		if ((params != null) && !params.isEmpty()) {
 59 			for (String key : params.keySet()) {
 60 				q.setParameter(key, params.get(key));
 61 			}
 62 		}
 63 		List<T> l = q.list();
 64 		if ((l != null) && (l.size() > 0)) {
 65 			return l.get(0);
 66 		}
 67 		return null;
 68 	}
 69 
 70 	@Override
 71 	public void delete(T o) {
 72 		if (o != null) {
 73 			this.getCurrentSession().delete(o);
 74 		}
 75 	}
 76 
 77 	@Override
 78 	public void update(T o) {
 79 		if (o != null) {
 80 			this.getCurrentSession().update(o);
 81 		}
 82 	}
 83 
 84 	@Override
 85 	public void saveOrUpdate(T o) {
 86 		if (o != null) {
 87 			this.getCurrentSession().saveOrUpdate(o);
 88 		}
 89 	}
 90 
 91 	@Override
 92 	public List<T> find(String hql) {
 93 		Query q = this.getCurrentSession().createQuery(hql);
 94 		return q.list();
 95 	}
 96 
 97 	@Override
 98 	public List<T> find(String hql, Map<String, Object> params) {
 99 		Query q = this.getCurrentSession().createQuery(hql);
100 		if ((params != null) && !params.isEmpty()) {
101 			for (String key : params.keySet()) {
102 				q.setParameter(key, params.get(key));
103 			}
104 		}
105 		return q.list();
106 	}
107 
108 	@Override
109 	public List<T> find(String hql, Map<String, Object> params, int page,
110 			int rows) {
111 		Query q = this.getCurrentSession().createQuery(hql);
112 		if ((params != null) && !params.isEmpty()) {
113 			for (String key : params.keySet()) {
114 				q.setParameter(key, params.get(key));
115 			}
116 		}
117 		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
118 	}
119 
120 	@Override
121 	public List<T> find(String hql, int page, int rows) {
122 		Query q = this.getCurrentSession().createQuery(hql);
123 		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
124 	}
125 
126 	@Override
127 	public Long count(String hql) {
128 		Query q = this.getCurrentSession().createQuery(hql);
129 		return (Long) q.uniqueResult();
130 	}
131 
132 	@Override
133 	public Long count(String hql, Map<String, Object> params) {
134 		Query q = this.getCurrentSession().createQuery(hql);
135 		if ((params != null) && !params.isEmpty()) {
136 			for (String key : params.keySet()) {
137 				q.setParameter(key, params.get(key));
138 			}
139 		}
140 		return (Long) q.uniqueResult();
141 	}
142 
143 	@Override
144 	public int executeHql(String hql) {
145 		Query q = this.getCurrentSession().createQuery(hql);
146 		return q.executeUpdate();
147 	}
148 
149 	@Override
150 	public int executeHql(String hql, Map<String, Object> params) {
151 		Query q = this.getCurrentSession().createQuery(hql);
152 		if ((params != null) && !params.isEmpty()) {
153 			for (String key : params.keySet()) {
154 				q.setParameter(key, params.get(key));
155 			}
156 		}
157 		return q.executeUpdate();
158 	}
159 
160 	@Override
161 	public List<Object[]> findBySql(String sql) {
162 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
163 		return q.list();
164 	}
165 
166 	@Override
167 	public List<Object[]> findBySql(String sql, int page, int rows) {
168 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
169 		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
170 	}
171 
172 	@Override
173 	public List<Object[]> findBySql(String sql, Map<String, Object> params) {
174 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
175 		if ((params != null) && !params.isEmpty()) {
176 			for (String key : params.keySet()) {
177 				q.setParameter(key, params.get(key));
178 			}
179 		}
180 		return q.list();
181 	}
182 
183 	@Override
184 	public List<Object[]> findBySql(String sql, Map<String, Object> params,
185 			int page, int rows) {
186 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
187 		if ((params != null) && !params.isEmpty()) {
188 			for (String key : params.keySet()) {
189 				q.setParameter(key, params.get(key));
190 			}
191 		}
192 		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
193 	}
194 
195 	@Override
196 	public int executeSql(String sql) {
197 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
198 		return q.executeUpdate();
199 	}
200 
201 	@Override
202 	public int executeSql(String sql, Map<String, Object> params) {
203 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
204 		if ((params != null) && !params.isEmpty()) {
205 			for (String key : params.keySet()) {
206 				q.setParameter(key, params.get(key));
207 			}
208 		}
209 		return q.executeUpdate();
210 	}
211 
212 	@Override
213 	public BigInteger countBySql(String sql) {
214 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
215 		return (BigInteger) q.uniqueResult();
216 	}
217 
218 	@Override
219 	public BigInteger countBySql(String sql, Map<String, Object> params) {
220 		SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
221 		if ((params != null) && !params.isEmpty()) {
222 			for (String key : params.keySet()) {
223 				q.setParameter(key, params.get(key));
224 			}
225 		}
226 		return (BigInteger) q.uniqueResult();
227 	}
228 
229 	@Override
230 	public void refresh(T o) {
231 		this.getCurrentSession().refresh(o);
232 
233 	}
234 
235 	@Override
236 	public void merge(T o) {
237 		this.getCurrentSession().merge(o);
238 	}
239 }
240 

JdbcBaseDaoImpl.java

  1 package com.jacezhu.dao.impl;
  2 
  3 import java.lang.reflect.Field;
  4 import java.sql.CallableStatement;
  5 import java.sql.Connection;
  6 import java.sql.PreparedStatement;
  7 import java.sql.ResultSet;
  8 import java.sql.ResultSetMetaData;
  9 import java.sql.SQLException;
 10 import java.sql.Statement;
 11 import java.util.ArrayList;
 12 import java.util.HashMap;
 13 import java.util.List;
 14 import java.util.Map;
 15 
 16 import javax.sql.DataSource;
 17 
 18 import org.springframework.stereotype.Repository;
 19 import com.jacezhu.dao.JdbcBaseDao;
 20 import com.jacezhu.framework.connectUtil.ConnUtil;
 21 import com.jacezhu.framework.connectUtil.DataSourceConnUtil;
 22 import com.jacezhu.framework.connectUtil.DruidDataSourceUtil;
 23 import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
 24 import com.jacezhu.framework.connectUtil.jdbcUtl.SqlParameter;
 25 
 26 @Repository
 27 public class JdbcBaseDaoImpl implements JdbcBaseDao {
 28 	/**
 29 	 * 获取连接
 30 	 */
 31 	static {
 32 		getConnection();
 33 	}
 34     /**
 35     * @author  刘军
 36     * @date 2016-3-19 上午11:14:17   37     * @version V1.0    38     * @Title: getStatement   39     * @Description: ( )   40     * @param @return
 41     * @param @throws SQLException    设定文件   42     * @return Connection    返回类型   43     * @throws   44      */
 45 	public Connection getStatement() throws SQLException {
 46 		Connection connection = null;
 47 		Statement statement = null;
 48 		// 仅当statement失效时才重新创建
 49 		if (statement == null || statement.isClosed() == true) {
 50 			statement = connection.createStatement(
 51 					ResultSet.TYPE_SCROLL_INSENSITIVE,
 52 					ResultSet.CONCUR_READ_ONLY);
 53 		}
 54 		return connection;
 55 	}
 56 
 57 	/**
 58 	 *
 59 	 * @Title: getConnection   60 	 * @Description: (得到数据库连接)   61 	 * @param @return    设定文件   62 	 * @return Connection    返回类型   63 	 * @throws   64 	 */
 65 	public static Connection getConnection() {
 66 		Connection connection = null;
 67 		try {
 68 			/**
 69 			 *  从 阿里巴巴 开源的数据库连接池中获取连接
 70 			 */
 71 			int dbType=0;
 72 			DataSource dataSource=DruidDataSourceUtil.getDataSource(dbType);
 73 			connection = dataSource.getConnection();
 74 			if (connection == null) {
 75 				/**
 76 				 *  连接C3P0 连接池
 77 				 */
 78 				connection = DataSourceConnUtil.getConnection();
 79 			}
 80 			if (connection == null) {
 81 				/**
 82 				 * 直接连接数据库
 83 				 */
 84 				connection = ConnUtil.getConn();
 85 			}
 86 		} catch (Exception e) {
 87 			e.printStackTrace();
 88 		}
 89 		return connection;
 90 	}
 91 
 92 
 93 	/**
 94 	 *
 95 	 * @Title: update   96 	 * @Description: (更新:update)   97 	 * @param @param sql
 98 	 * @param @param obj
 99 	 * @param @param isGenerateKey
100 	 * @param @return    设定文件  101 	 * @return boolean    返回类型  102 	 * @throws  103 	 */
104 	public boolean update(String sql, Object[] obj, boolean isGenerateKey) {
105 		Connection conn = null;
106 		PreparedStatement pstmt = null;
107 		boolean bFlag = false;
108 		try {
109 			conn = JdbcBaseDaoImpl.getConnection();
110 			pstmt = isGenerateKey ? conn.prepareStatement(sql,
111 					Statement.RETURN_GENERATED_KEYS) : conn
112 					.prepareStatement(sql);
113 			for (int i = 0; i < obj.length; i++) {
114 				pstmt.setObject(i + 1, obj[i]);
115 			}
116 			conn.setAutoCommit(false);//JDBC 事务管理
117 			int i = pstmt.executeUpdate();
118 			conn.commit();//JDBC 事务管理
119 			if (i > 0)
120 				bFlag = true;
121 		} catch (SQLException ex) {
122 			ex.printStackTrace();
123 			try {
124 				conn.rollback();//JDBC 事务管理
125 			} catch (SQLException e) {
126 				e.printStackTrace();
127 			}
128 		} finally {
129 			try {
130 				conn.close();
131 				pstmt.close();
132 			} catch (SQLException ex) {
133 				ex.printStackTrace();
134 			}
135 		}
136 		return bFlag;
137 	}
138 	/**
139 	 *
140 	 * @Title: updateByPreparedStatement  增加、删除、改
141 	 * @Description: (增加、删除、改)  142 	 * @param @param sql
143 	 * @param @param params
144 	 * @param @return    设定文件  145 	 * @return boolean    返回类型  146 	 * @throws  147 	 */
148 	public boolean updateByPreparedStatement(String sql, List<Object> params) {
149 		boolean flag = false;
150 		Connection connection = null;
151 		PreparedStatement pstmt = null;
152 		int result = -1;
153 		try {
154 			connection = JdbcBaseDaoImpl.getConnection();
155 			pstmt = connection.prepareStatement(sql);
156 			int index = 1;
157 			if (params != null && !params.isEmpty()) {
158 				for (int i = 0; i < params.size(); i++) {
159 					pstmt.setObject(index++, params.get(i));
160 				}
161 			}
162 			result = pstmt.executeUpdate();
163 			connection.commit();//JDBC 事务管理
164 			flag = result > 0 ? true : false;
165 		} catch (SQLException e) {
166 			try {
167 				connection.rollback();//JDBC 事务管理
168 			} catch (SQLException e1) {
169 				e1.printStackTrace();
170 			}
171 			e.printStackTrace();
172 		} finally {
173 			try {
174 				pstmt.close();
175 				connection.close();
176 			} catch (SQLException e) {
177 				e.printStackTrace();
178 			}
179 
180 		}
181 		return flag;
182 	}
183 
184 
185 
186 	/**
187 	 * insert update delete SQL语句的执行的统一方法
188 	 *
189 	 * @param sql
190 	 *            SQL语句
191 	 * @param params
192 	 *            参数数组,若没有参数则为null
193 	 * @return 受影响的行数
194 	 */
195 	public int executeUpdate(String sql, Object[] params) {
196 		PreparedStatement preparedStatement = null;
197 		// 受影响的行数
198 		int affectedLine = 0;
199 		Connection connection = null;
200 		try {
201 			// 获得连接
202 			connection = JdbcBaseDaoImpl.getConnection();
203 			// 调用SQL
204 			preparedStatement = connection.prepareStatement(sql);
205 			// 参数赋值
206 			if (params != null) {
207 				for (int i = 0; i < params.length; i++) {
208 					preparedStatement.setObject(i + 1, params[i]);
209 				}
210 			}
211 			// 执行
212 			affectedLine = preparedStatement.executeUpdate();
213 			connection.commit();// 提交事务
214 		} catch (SQLException e) {
215 			System.out.println(e.getMessage());
216 			try {
217 				connection.rollback();//JDBC 事务管理
218 			} catch (SQLException e1) {
219 				e1.printStackTrace();
220 			}
221 		} finally {
222 			// 释放资源
223 			close(connection, preparedStatement, null);
224 		}
225 		return affectedLine;
226 	}
227 
228 
229 
230 	/**
231 	 *
232 	 * @Title: query  233 	 * @Description: (这里用一句话描述这个方法的作用)  234 	 * @param @param sql
235 	 * @param @param obj
236 	 * @param @param mapper
237 	 * @param @return    设定文件  238 	 * @return List<? extends Object>    返回类型  239 	 * @throws  240 	 */
241 	public List<? extends Object> query(String sql, Object[] obj,
242 			ObjectMapper mapper) {
243 		Object o = null;
244 		List<Object> list = new ArrayList<Object>();
245 		Connection conn = null;
246 		PreparedStatement pstmt = null;
247 		try {
248 			conn = JdbcBaseDaoImpl.getConnection();
249 			pstmt = conn.prepareStatement(sql);
250 			for (int i = 0; i < obj.length; i++) {
251 				pstmt.setObject(i + 1, obj[i]);
252 			}
253 			ResultSet rs = pstmt.executeQuery();
254 			while (rs.next()) {
255 				o = mapper.mapping(rs);
256 				list.add(o);
257 			}
258 		} catch (SQLException ex) {
259 			ex.printStackTrace();
260 		} finally {
261 			try {
262 				pstmt.close();
263 				conn.close();
264 			} catch (SQLException ex) {
265 				ex.printStackTrace();
266 			}
267 		}
268 		return list;
269 	}
270 	/**
271 	 *
272 	* @author   liujun<1136808529@qq.coom>
273 	* @date 2016-5-12 下午1:54:42  274 	* @version V1.0   275 	* @Title: query  276 	* @Description: (
277 	 *
278 	 *)  279 	* @param @param sql
280 	* @param @param obj
281 	* @param @param mapper
282 	* @param @return    设定文件  283 	* @return List<? extends Object>    返回类型  284 	* @throws  285 	 */
286 	public List<? extends Object> query(String sql, List obj,
287 			ObjectMapper mapper) {
288 		Object o = null;
289 		List<Object> list = new ArrayList<Object>();
290 		Connection conn = null;
291 		PreparedStatement pstmt = null;
292 		try {
293 			conn = JdbcBaseDaoImpl.getConnection();
294 			pstmt = conn.prepareStatement(sql);
295 			for (int i = 0; i < obj.size(); i++) {
296 				pstmt.setObject(i + 1, obj.get(i));
297 			}
298 			ResultSet rs = pstmt.executeQuery();
299 			while (rs.next()) {
300 				o = mapper.mapping(rs);
301 				list.add(o);
302 			}
303 		} catch (SQLException ex) {
304 			ex.printStackTrace();
305 		} finally {
306 			try {
307 				pstmt.close();
308 				conn.close();
309 			} catch (SQLException ex) {
310 				ex.printStackTrace();
311 			}
312 		}
313 		return list;
314 	}
315 
316      /**
317       *
318      * @Title: returnTableCount  319      * @Description: ( select count(*)from table 的总数据条数)  320      * @param @param table
321      * @param @return    设定文件  322      * @return int    返回类型  323      * @throws  324       */
325 	public int returnTableCount(String table){
326 		String sql="select count(*) as counts from "+table+"";
327 		Connection conn = null;
328 		ResultSet resultSet = null;
329 		Statement pstmt = null;
330 		int count=0;
331 		try {
332 			conn = JdbcBaseDaoImpl.getConnection();
333 			pstmt = conn.createStatement();
334 			resultSet=pstmt.executeQuery(sql);
335 			if(resultSet.next()){
336 				count=resultSet.getInt("counts");
337 			}
338 		} catch (Exception e) {
339 			e.printStackTrace();
340 		}finally{
341 			try {
342 				resultSet.close();
343 				pstmt.close();
344 				conn.close();
345 			} catch (SQLException ex) {
346 				ex.printStackTrace();
347 			}
348 		}
349 		return count;
350 
351 	}
352 	/**
353 	 *
354 	* @author   liujun<1136808529@qq.coom>
355 	* @date 2016-5-12 下午11:19:02  356 	* @version V1.0   357 	* @Title: Count  358 	* @Description: (
359 	 *  统计有多少记录
360 	 *)  361 	* @param @param sql
362 	* @param @return    设定文件  363 	* @return int    返回类型  364 	* @throws  365 	 */
366 	public long  Count(String sql){
367 		if(sql==null || sql==""){
368 			 return (long)0;
369 		}
370 		Connection conn = null;
371 		ResultSet resultSet = null;
372 		Statement pstmt = null;
373 		long count=0;
374 		try {
375 			conn = JdbcBaseDaoImpl.getConnection();
376 			pstmt = conn.createStatement();
377 			resultSet=pstmt.executeQuery(sql);
378 			if(resultSet.next()){
379 				count=resultSet.getInt("counts");
380 			}
381 		} catch (Exception e) {
382 			e.printStackTrace();
383 		}finally{
384 			try {
385 				resultSet.close();
386 				pstmt.close();
387 				conn.close();
388 			} catch (SQLException ex) {
389 				ex.printStackTrace();
390 			}
391 		}
392 		return count;
393 
394 	}
395 
396 	/**
397 	 *
398 	 * @Title: findSimpleResult  获取最后一条(单条)记录
399 	 * @Description: (查询单条记录)  400 	 * @param @param sql
401 	 * @param @param params
402 	 * @param @return    设定文件  403 	 * @return Map<String,Object>    返回类型  404 	 * @throws  405 	 */
406 	public Map<String, Object> findSimpleResult(String sql, List<Object> params) {
407 		Map<String, Object> map = new HashMap<String, Object>();
408 		Connection connection = null;
409 		PreparedStatement pstmt = null;
410 		ResultSet resultSet = null;
411 		int index = 1;
412 		try {
413 			connection = JdbcBaseDaoImpl.getConnection();
414 			pstmt = connection.prepareStatement(sql);
415 			if (params != null && !params.isEmpty()) {
416 				for (int i = 0; i < params.size(); i++) {
417 					pstmt.setObject(index++, params.get(i));
418 				}
419 			}
420 			resultSet = pstmt.executeQuery();// 返回查询结果
421 			ResultSetMetaData metaData = resultSet.getMetaData();
422 			int col_len = metaData.getColumnCount();
423 			while (resultSet.next()) {
424 			 	for (int i = 0; i < col_len; i++) {
425 					String cols_name = metaData.getColumnName( i +  1);
426 					Object cols_value = resultSet.getObject(cols_name);
427 					if (cols_value == null) {
428 						cols_value = "";
429 					}
430 					map.put(cols_name, cols_value);
431 			 	}
432 			}
433 		} catch (SQLException e) {
434 			e.printStackTrace();
435 		} finally {
436 			try {
437 				resultSet.close();
438 				pstmt.close();
439 				connection.close();
440 			} catch (SQLException e) {
441 				e.printStackTrace();
442 			}
443 		}
444 		return map;
445 	}
446 	/**
447 	 * 获取结果集,并将结果放在List中
448 	 *
449 	 * @param sql
450 	 *            SQL语句
451 	 * @return List 结果集
452 	 */
453 	public List<Object> excuteQuery(String sql, Object[] params) {
454 		// 创建List
455 		List<Object> list = new ArrayList<Object>();
456 		Connection connection = null;
457 		ResultSet rs = null;
458 		// 创建ResultSetMetaData对象
459 		ResultSetMetaData rsmd = null;
460 		// 结果集列数
461 		int columnCount = 0;
462 		try {
463 			// 获得连接
464 			connection = JdbcBaseDaoImpl.getConnection();
465 			// 执行SQL获得结果集
466 			rs = executeQueryRS(sql, params);
467 			// 将ResultSet的结果保存到List中
468 			while (rs.next()) {
469 				rsmd = rs.getMetaData();
470 				// 获得结果集列数
471 				columnCount = rsmd.getColumnCount();
472 				Map<String, Object> map = new HashMap<String, Object>();
473 				for (int i = 1; i <= columnCount; i++) {
474 					map.put(rsmd.getColumnLabel(i), rs.getObject(i));
475 				}
476 				list.add(map);
477 			}
478 		} catch (SQLException e) {
479 			e.printStackTrace();
480 			System.out.println(e.getMessage());
481 		} finally {
482 			// 关闭所有资源
483 			try {
484 				rs.close();
485 				connection.close();
486 			} catch (Exception e) {
487 				e.printStackTrace();
488 			}
489 
490 		}
491 		return list;
492 	}
493 
494 	/**
495 	 * SQL 查询将查询结果直接放入ResultSet中
496 	 *
497 	 * @param sql
498 	 *            SQL语句
499 	 * @param params
500 	 *            参数数组,若没有参数则为null
501 	 * @return 结果集
502 	 */
503 	private ResultSet executeQueryRS(String sql, Object[] params) {
504 		Connection connection = null;
505 		PreparedStatement preparedStatement = null;
506 		ResultSet resultSet = null;
507 		try {
508 			// 获得连接
509 			connection = JdbcBaseDaoImpl.getConnection();
510 			// 调用SQL
511 			preparedStatement = connection.prepareStatement(sql);
512 			// 参数赋值
513 			if (params != null) {
514 				for (int i = 0; i < params.length; i++) {
515 					preparedStatement.setObject(i + 1, params[i]);
516 				}
517 			}
518 			// 执行
519 			resultSet = preparedStatement.executeQuery();
520 
521 		} catch (SQLException e) {
522 			System.out.println(e.getMessage());
523 		} finally {
524 			try {
525 				resultSet.close();
526 				preparedStatement.close();
527 				connection.close();
528 			} catch (SQLException e) {
529 				e.printStackTrace();
530 			}
531 		}
532 
533 		return resultSet;
534 	}
535 
536 	/**
537 	 *
538 	 * @Title: findModeResult  查询多条记录
539 	 * @Description: (查询多条记录)  540 	 * @param @param sql
541 	 * @param @param params
542 	 * @param @return
543 	 * @param @throws SQLException    设定文件  544 	 * @return List<Map<String,Object>>    返回类型  545 	 * @throws  546 	 */
547 	public List<Map<String, Object>> findModeResult(String sql,
548 			List<Object> params) {
549 		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
550 		Connection connection = null;
551 		PreparedStatement pstmt = null;
552 		ResultSet resultSet = null;
553 		int index = 1;
554 		try {
555 			connection = JdbcBaseDaoImpl.getConnection();
556 			pstmt = connection.prepareStatement(sql);
557 			if (params != null && !params.isEmpty()) {
558 				for (int i = 0; i < params.size(); i++) {
559 					pstmt.setObject(index++, params.get(i));
560 				}
561 			}
562 			resultSet = pstmt.executeQuery();
563 			ResultSetMetaData metaData = resultSet.getMetaData();
564 			int cols_len = metaData.getColumnCount();
565 			while (resultSet.next()) {
566 				Map<String, Object> map = new HashMap<String, Object>();
567 				for (int i = 0; i < cols_len; i++) {
568 					String cols_name = metaData.getColumnName(i + 1);
569 					Object cols_value = resultSet.getObject(cols_name);
570 					if (cols_value == null) {
571 						cols_value = "";
572 					}
573 					map.put(cols_name, cols_value);
574 				}
575 				list.add(map);
576 			}
577 		} catch (SQLException e) {
578 			e.printStackTrace();
579 		} finally {
580 			try {
581 				resultSet.close();
582 				pstmt.close();
583 				connection.close();
584 			} catch (SQLException e) {
585 				e.printStackTrace();
586 			}
587 		}
588 
589 		return list;
590 	}
591 
592 	/**
593 	 * SQL 查询将查询结果:一行一列
594 	 *
595 	 * @param sql
596 	 *            SQL语句
597 	 * @param params
598 	 *            参数数组,若没有参数则为null
599 	 * @return 结果集
600 	 */
601 	public Object executeQuerySingle(String sql, Object[] params) {
602 		Object object = null;
603 		Connection connection = null;
604 		PreparedStatement preparedStatement = null;
605 		ResultSet resultSet = null;
606 		try {
607 			// 获得连接
608 			connection = JdbcBaseDaoImpl.getConnection();
609 			// 调用SQL
610 			preparedStatement = connection.prepareStatement(sql);
611 			// 参数赋值
612 			if (params != null) {
613 				for (int i = 0; i < params.length; i++) {
614 					preparedStatement.setObject(i + 1, params[i]);
615 				}
616 			}
617 			// 执行
618 			resultSet = preparedStatement.executeQuery();
619 			if (resultSet.next()) {
620 				object = resultSet.getObject(1);
621 			}
622 		} catch (SQLException e) {
623 			System.out.println(e.getMessage());
624 		} finally {
625 			close(connection, preparedStatement, resultSet);
626 		}
627 		return object;
628 	}
629 
630 
631 
632 	/**
633 	 *
634 	 * @Title: findSimpleRefResult  通过反射机制查询单条记录
635 	 * @Description: (通过反射机制查询单条记录)  636 	 * @param @param sql
637 	 * @param @param params
638 	 * @param @param cls
639 	 * @param @return
640 	 * @param @throws Exception    设定文件  641 	 * @return T    返回类型  642 	 * @throws  643 	 */
644 	public   <T> T findSimpleRefResult(String sql, List<Object> params,
645 			Class<T> cls) {
646 		T resultObject = null;
647 		Connection connection = null;
648 		PreparedStatement pstmt = null;
649 		ResultSet resultSet = null;
650 		int index = 1;
651 		try {
652 			connection = JdbcBaseDaoImpl.getConnection();
653 			pstmt = connection.prepareStatement(sql);
654 			if (params != null && !params.isEmpty()) {
655 				for (int i = 0; i < params.size(); i++) {
656 					pstmt.setObject(index++, params.get(i));
657 				}
658 			}
659 			resultSet = pstmt.executeQuery();
660 			ResultSetMetaData metaData = resultSet.getMetaData();
661 			int cols_len = metaData.getColumnCount();
662 			while (resultSet.next()) {
663 				// 通过反射机制创建一个实例
664 				resultObject = cls.newInstance();
665 				for (int i = 0; i < cols_len; i++) {
666 					String cols_name = metaData.getColumnName(i + 1);
667 					Object cols_value = resultSet.getObject(cols_name);
668 					if (cols_value == null) {
669 						cols_value = "";
670 					}
671 					Field field = cls.getDeclaredField(cols_name);
672 					field.setAccessible(true); // 打开javabean的访问权限
673 					field.set(resultObject, cols_value);
674 				}
675 			}
676 		} catch (Exception e) {
677 			e.printStackTrace();
678 		} finally {
679 			try {
680 				resultSet.close();
681 				pstmt.close();
682 				connection.close();
683 			} catch (SQLException e) {
684 				e.printStackTrace();
685 			}
686 		}
687 		return resultObject;
688 
689 	}
690 
691 	/**
692 	 * 通过反射机制查询多条记录
693 	 *
694 	 * @param sql
695 	 * @param params
696 	 * @param cls
697 	 * @return
698 	 * @throws Exception
699 	 */
700 	public <T> List<T> findMoreRefResult(String sql, List<Object> params,
701 			Class<T> cls) {
702 		List<T> list = new ArrayList<T>();
703 		Connection connection = null;
704 		PreparedStatement pstmt = null;
705 		ResultSet resultSet = null;
706 		int index = 1;
707 		try {
708 			connection = JdbcBaseDaoImpl.getConnection();
709 			pstmt = connection.prepareStatement(sql);
710 			if (params != null && !params.isEmpty()) {
711 				for (int i = 0; i < params.size(); i++) {
712 					pstmt.setObject(index++, params.get(i));
713 				}
714 			}
715 			resultSet = pstmt.executeQuery();
716 			ResultSetMetaData metaData = resultSet.getMetaData();
717 			int cols_len = metaData.getColumnCount();
718 			while (resultSet.next()) {
719 				// 通过反射机制创建一个实例
720 				T resultObject = cls.newInstance();
721 				for (int i = 0; i < cols_len; i++) {
722 					String cols_name = metaData.getColumnName(i + 1);
723 					Object cols_value = resultSet.getObject(cols_name);
724 					if (cols_value == null) {
725 						cols_value = "";
726 					}
727 					Field field = cls.getDeclaredField(cols_name);
728 					field.setAccessible(true); // 打开javabean的访问权限
729 					field.set(resultObject, cols_value);
730 				}
731 				list.add(resultObject);
732 			}
733 		} catch (Exception e) {
734 			e.printStackTrace();
735 		} finally {
736 			try {
737 				resultSet.close();
738 				pstmt.close();
739 				connection.close();
740 			} catch (SQLException e) {
741 				e.printStackTrace();
742 			}
743 
744 		}
745 		return list;
746 	}
747 
748 	/**
749 	 *
750 	 * @Title: find  751 	 * @Description: (查询一条记录)  752 	 * @param @param sql
753 	 * @param @param obj
754 	 * @param @param mapper
755 	 * @param @return    设定文件  756 	 * @return Object    返回类型  757 	 * @throws  758 	 */
759 	public Object find(String sql, Object[] obj, ObjectMapper mapper) {
760 		Object o = null;
761 		Connection conn = null;
762 		PreparedStatement pstmt = null;
763 		try {
764 			conn = JdbcBaseDaoImpl.getConnection();
765 			pstmt = conn.prepareStatement(sql);
766 			for (int i = 0; i < obj.length; i++) {
767 				pstmt.setObject(i + 1, obj[i]);
768 				ResultSet rs = pstmt.executeQuery();
769 				if (rs.next()) {
770 					o = mapper.mapping(rs);
771 				}
772 			}
773 		} catch (Exception ex) {
774 			ex.printStackTrace();
775 		} finally {
776 			try {
777 				pstmt.close();
778 				conn.close();
779 			} catch (SQLException ex) {
780 				ex.printStackTrace();
781 			}
782 		}
783 		return o;
784 	}
785 	/**
786 	 *
787 	* @author   liujun<1136808529@qq.coom>
788 	* @date 2016-5-14 下午1:17:28  789 	* @version V1.0   790 	* @Title: find  791 	* @Description: (
792 	 *  查询一条记录
793 	 *)  794 	* @param @param sql
795 	* @param @param obj
796 	* @param @param mapper
797 	* @param @return    设定文件  798 	* @return Object    返回类型  799 	* @throws  800 	 */
801 	public Object find(String sql, List obj, ObjectMapper mapper) {
802 		Object o = null;
803 		Connection conn = null;
804 		PreparedStatement pstmt = null;
805 		try {
806 			conn = JdbcBaseDaoImpl.getConnection();
807 			pstmt = conn.prepareStatement(sql);
808 			for (int i = 0; i < obj.size(); i++) {
809 				pstmt.setObject(i + 1, obj.get(i));
810 				ResultSet rs = pstmt.executeQuery();
811 				if (rs.next()) {
812 					o = mapper.mapping(rs);
813 				}
814 			}
815 		} catch (Exception ex) {
816 			ex.printStackTrace();
817 		} finally {
818 			try {
819 				pstmt.close();
820 				conn.close();
821 			} catch (SQLException ex) {
822 				ex.printStackTrace();
823 			}
824 		}
825 		return o;
826 	}
827 
828 
829 	/**
830 	 *
831 	 * @Title: executeQuery  统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源
832 	 * @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源)  833 	 * @param @param sql
834 	 * @param @param parameters
835 	 * @param @return    设定文件  836 	 * @return ArrayList    返回类型  837 	 * @throws  838 	 */
839 	@SuppressWarnings({ "rawtypes", "unchecked" })
840 	public ArrayList executeQuery(String sql, String[] parameters) {
841 		ArrayList results = new ArrayList();
842 		// 定义需要的变量
843 		Connection conn = null;
844 		PreparedStatement ps = null;
845 		ResultSet rs = null;
846 
847 		try {
848 			// 获得连接
849 			conn = JdbcBaseDaoImpl.getConnection();
850 			ps = conn.prepareStatement(sql);
851 
852 			if (parameters != null) {
853 				for (int i = 0; i < parameters.length; i++) {
854 					ps.setString(i + 1, parameters[i]);
855 				}
856 			}
857 			rs = ps.executeQuery();
858 			ResultSetMetaData rsmd = rs.getMetaData();
859 			int column = rsmd.getColumnCount();
860 			while (rs.next()) {
861 				Object[] objects = new Object[column];
862 				for (int i = 1; i <= column; i++) {
863 					objects[i - 1] = rs.getObject(i);
864 				}
865 				results.add(objects);
866 			}
867 		} catch (SQLException e) {
868 			e.printStackTrace();
869 			throw new RuntimeException(e.getMessage());
870 		} finally {
871 			try {
872 				rs.close();
873 				ps.close();
874 				conn.close();
875 			} catch (SQLException e) {
876 				e.printStackTrace();
877 			}
878 		}
879 		return results;
880 	}
881 
882 
883 	/**
884 	 *
885 	 * @Title: executeQuery  by statement
886 	 * @Description: (执行 查询sql 获取结果集)  887 	 * @param @param sql
888 	 * @param @return statement resultSet
889 	 * @param @throws SQLException    设定文件  890 	 * @return ResultSet    返回类型  891 	 * @throws  892 	 */
893 	public ResultSet executeQuery(String sql) {
894 		Statement statement = null;
895 		ResultSet resultSet = null;
896 		Connection connection = null;
897 		try {
898 			connection = getStatement();
899 			if (resultSet != null && resultSet.isClosed() == false) {
900 				resultSet.close();
901 			}
902 			resultSet = null;
903 			resultSet = statement.executeQuery(sql);
904 		} catch (Exception e) {
905 			e.printStackTrace();
906 		} finally {
907 
908 		}
909 		return resultSet;
910 	}
911 
912 
913 	//-------------------------------------------对象化---------------
914 	  /**
915      * 将一条记录转成一个对象
916      *
917      * @param cls
918      *            泛型类型
919      * @param rs
920      *            ResultSet对象
921      * @return 泛型类型对象
922      * @throws InstantiationException
923      * @throws IllegalAccessException
924      * @throws SQLException
925      */
926     private static <T> T executeResultSet(Class<T> cls, ResultSet rs)
927             throws InstantiationException, IllegalAccessException, SQLException {
928         T obj = cls.newInstance();
929         ResultSetMetaData rsm = rs.getMetaData();
930         int columnCount = rsm.getColumnCount();
931         // Field[] fields = cls.getFields();
932         Field[] fields = cls.getDeclaredFields();
933         for (int i = 0; i < fields.length; i++) {
934             Field field = fields[i];
935             String fieldName = field.getName();
936             for (int j = 1; j <= columnCount; j++) {
937                 String columnName = rsm.getColumnName(j);
938                 if (fieldName.equalsIgnoreCase(columnName)) {
939                     Object value = rs.getObject(j);
940                     field.setAccessible(true);
941                     field.set(obj, value);
942                     break;
943                 }
944             }
945         }
946         return obj;
947     }
948 
949 
950 
951 	/**
952 	 *
953 	* @author   liujun<1136808529@qq.coom>
954 	* @date 2016-5-17 上午11:33:28  955 	* @version V1.0   956 	* @Title: getSeq  957 	* @Description:  (
958 	 *  获取sequence 序列号
959 	 *)  960 	* @param @param sequenceName
961 	* @param @return    设定文件  962 	* @return int    返回类型  963 	* @throws  964 	 */
965     public   int getSeq(String sequenceName){
966 		 int count = 0;
967 		  Connection conn = getConnection();
968 		  String sql = "SELECT nextval('"+sequenceName+"');";
969 		  PreparedStatement ptmt = null;
970 		  ResultSet rs = null;
971 		  try {
972 		    ptmt = conn.prepareStatement(sql);
973 		    rs = ptmt.executeQuery();
974 		    while (rs.next()) {
975 		      count = rs.getInt(1);
976 		    }
977 		    System.out.println(count);
978 		  } catch (SQLException e) {
979 		    e.printStackTrace();
980 		  } finally {
981 			  try {
982 				  rs.close();
983 				  ptmt.close();
984 				  conn.close();
985 			} catch (SQLException e) {
986 				e.printStackTrace();
987 			}
988 
989 		  }
990 
991 		return count;
992 	}
993 
994 
995 
996 
997 
998 
999 //----------------------存储过程调用-------------------------------------------
1000 
1001 
1002 	/**
1003 	 * 存储过程带有一个输出参数的方法
1004 	 *
1005 	 * @param sql
1006 	 *            存储过程语句
1007 	 * @param params
1008 	 *            参数数组
1009 	 * @param outParamPos
1010 	 *            输出参数位置
1011 	 * @param SqlType
1012 	 *            输出参数类型
1013 	 * @return 输出参数的值
1014 	 */
1015 	public Object executeQuery(String sql, Object[] params, int outParamPos,
1016 			int SqlType) {
1017 		Connection connection = null;
1018 		Statement statement = null;
1019 		Object object = null;
1020 		CallableStatement callableStatement = null;
1021 		try {
1022 			connection = JdbcBaseDaoImpl.getConnection();
1023 			// 调用存储过程
1024 			callableStatement = connection.prepareCall(sql);
1025 			// 给参数赋值
1026 			if (params != null) {
1027 				for (int i = 0; i < params.length; i++) {
1028 					callableStatement.setObject(i + 1, params[i]);
1029 				}
1030 			}
1031 			// 注册输出参数
1032 			callableStatement.registerOutParameter(outParamPos, SqlType);
1033 			// 执行
1034 			callableStatement.execute();
1035 			// 得到输出参数
1036 			object = callableStatement.getObject(outParamPos);
1037 		} catch (SQLException e) {
1038 			System.out.println(e.getMessage());
1039 		} finally {
1040 			// 释放资源
1041 			closeAll(connection, null, callableStatement, null);
1042 		}
1043 		return object;
1044 	}
1045 
1046     /**
1047      * 执行不返回结果集的存储过程
1048      *
1049      * @param sql
1050      *            存储过程名称
1051      * @param params
1052      *            存储过程参数
1053      * @throws ClassNotFoundException
1054      * @throws SQLException
1055      */
1056     public   void executeNonQuery(String sql, SqlParameter... params) {
1057         Connection con = null;
1058         CallableStatement cs = null;
1059         try {
1060             con = getConnection();
1061             cs = con.prepareCall(sql);
1062             setSqlParameter(cs, params);
1063             cs.executeUpdate();
1064             getSqlParameter(cs, params);
1065         } catch (Exception e) {
1066             e.printStackTrace();
1067         } finally {
1068         	close3(con, cs, null);
1069         }
1070     }
1071 
1072     /**
1073      * 执行Insert语句,返回Insert成功之后标识列的值
1074      *
1075      * @param sql
1076      * @return
1077      * @throws ClassNotFoundException
1078      * @throws SQLException
1079      */
1080     public   int executeIdentity(String sql) {
1081         int identity = -1;
1082         Connection con = null;
1083         Statement ps = null;
1084         ResultSet rs = null;
1085         try {
1086             con = getConnection();
1087             ps = con.createStatement();
1088             ps.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
1089             rs = ps.getGeneratedKeys();
1090             if (rs.next()) {
1091                 // identity = rs.getInt("GENERATED_KEYS");
1092                 identity = rs.getInt(1);
1093             }
1094         } catch (Exception e) {
1095             e.printStackTrace();
1096         } finally {
1097             close3(con, ps, null);
1098         }
1099         return identity;
1100     }
1101     /**
1102      * 执行不返回结果集的存储过程
1103      *
1104      * @param sql
1105      *            存储过程名称
1106      * @param params
1107      *            存储过程参数
1108      * @throws ClassNotFoundException
1109      * @throws SQLException
1110      */
1111     public   void executeNonQuery1(String sql, SqlParameter... params) {
1112         Connection con = null;
1113         CallableStatement cs = null;
1114         try {
1115             con = getConnection();
1116             cs = con.prepareCall(sql);
1117             setSqlParameter(cs, params);
1118             cs.executeUpdate();
1119             getSqlParameter(cs, params);
1120         } catch (Exception e) {
1121             e.printStackTrace();
1122         } finally {
1123             close3(con, cs, null);
1124         }
1125     }
1126     /**
1127      * 执行返回聚合函数的操作
1128      *
1129      * @param sql
1130      *            含有聚合函数的SQL语句
1131      * @return 聚合函数的执行结果
1132      * @throws SQLException
1133      * @throws ClassNotFoundException
1134      */
1135     public   int executeScalar(String sql) {
1136         int result = -1;
1137         Connection con = null;
1138         PreparedStatement ps = null;
1139         ResultSet rs = null;
1140         try {
1141             con = getConnection();
1142             ps = con.prepareStatement(sql);
1143             rs = ps.executeQuery();
1144             if (rs.next()) {
1145                 result = rs.getInt(1);
1146             }
1147         } catch (Exception e) {
1148             e.printStackTrace();
1149         } finally {
1150             close3(con, ps, rs);
1151         }
1152         return result;
1153     }
1154     /**
1155      * 执行返回泛型集合的SQL语句
1156      *
1157      * @param cls
1158      *            泛型类型
1159      * @param sql
1160      *            查询SQL语句
1161      * @return 泛型集合
1162      * @throws ClassNotFoundException
1163      * @throws SQLException
1164      * @throws InstantiationException
1165      * @throws IllegalAccessException
1166      */
1167     public   <T> List<T> executeList(Class<T> cls, String sql) {
1168         List<T> list = new ArrayList<T>();
1169         Connection con = null;
1170         PreparedStatement ps = null;
1171         ResultSet rs = null;
1172         try {
1173             con = getConnection();
1174             ps = con.prepareStatement(sql);
1175             rs = ps.executeQuery();
1176             while (rs.next()) {
1177                 T obj = executeResultSet(cls, rs);
1178                 list.add(obj);
1179             }
1180         } catch (Exception e) {
1181             e.printStackTrace();
1182         } finally {
1183             close3(con, ps, rs);
1184         }
1185         return list;
1186     }
1187     /**
1188      * 执行返回泛型集合的存储过程
1189      *
1190      * @param cls
1191      *            泛型类型
1192      * @param sql
1193      *            存储过程名称
1194      * @param params
1195      *            存储过程参数
1196      * @return 泛型集合
1197      * @throws ClassNotFoundException
1198      * @throws SQLException
1199      * @throws InstantiationException
1200      * @throws IllegalAccessException
1201      */
1202     public   <T> List<T> executeList(Class<T> cls, String sql,
1203             SqlParameter... params) {
1204         List<T> list = new ArrayList<T>();
1205         Connection con = null;
1206         CallableStatement cs = null;
1207         ResultSet rs = null;
1208         try {
1209             con = getConnection();
1210             cs = con.prepareCall(sql);
1211             setSqlParameter(cs, params);
1212             rs = cs.executeQuery();
1213             while (rs.next()) {
1214                 T obj = executeResultSet(cls, rs);
1215                 list.add(obj);
1216             }
1217         } catch (Exception e) {
1218             e.printStackTrace();
1219         } finally {
1220             close3(con, cs, rs);
1221         }
1222         return list;
1223     }
1224     /**
1225      * 执行返回泛型类型对象的SQL语句
1226      *
1227      * @param cls
1228      *            泛型类型
1229      * @param sql
1230      *            SQL语句
1231      * @return 泛型类型对象
1232      * @throws SQLException
1233      * @throws ClassNotFoundException
1234      * @throws InstantiationException
1235      * @throws IllegalAccessException
1236      */
1237     public   <T> T executeEntity(Class<T> cls, String sql) {
1238         T obj = null;
1239         Connection con = null;
1240         PreparedStatement ps = null;
1241         ResultSet rs = null;
1242         try {
1243             con = getConnection();
1244             ps = con.prepareStatement(sql);
1245             rs = ps.executeQuery();
1246             while (rs.next()) {
1247                 obj = executeResultSet(cls, rs);
1248                 break;
1249             }
1250         } catch (Exception e) {
1251             e.printStackTrace();
1252         } finally {
1253             close3(con, ps, rs);
1254         }
1255         return obj;
1256     }
1257     /**
1258      * 执行返回泛型类型对象的存储过程
1259      *
1260      * @param cls
1261      *            泛型类型
1262      * @param sql
1263      *            SQL语句
1264      * @param params
1265      *            存储过程参数
1266      * @return 泛型类型对象
1267      * @throws SQLException
1268      * @throws ClassNotFoundException
1269      * @throws InstantiationException
1270      * @throws IllegalAccessException
1271      */
1272     public   <T> T executeEntity(Class<T> cls, String sql,
1273             SqlParameter... params) {
1274         T obj = null;
1275         Connection con = null;
1276         CallableStatement cs = null;
1277         ResultSet rs = null;
1278         try {
1279             con = getConnection();
1280             cs = con.prepareCall(sql);
1281             setSqlParameter(cs, params);
1282             rs = cs.executeQuery();
1283             while (rs.next()) {
1284                 obj = executeResultSet(cls, rs);
1285                 break;
1286             }
1287         } catch (Exception e) {
1288             e.printStackTrace();
1289         } finally {
1290             close3(con, cs, rs);
1291         }
1292         return obj;
1293     }
1294 
1295     /**
1296      * 设置存储过程参数名称,参数值,参数方向
1297      *
1298      * @param cs
1299      * @param params
1300      * @throws SQLException
1301      */
1302     private   void setSqlParameter(CallableStatement cs,
1303             SqlParameter... params) throws SQLException {
1304         if (params != null) {
1305             for (SqlParameter param : params) {
1306                 if (param.OutPut) {
1307                     String paramName = param.Name;
1308                     if (paramName == null || paramName.equals("")) {
1309                         cs.registerOutParameter(1, param.Type);// 设置返回类型参数
1310                     } else {
1311                         cs.registerOutParameter(paramName, param.Type);// 设置输出类型参数
1312                     }
1313                 } else {
1314                     cs.setObject(param.Name, param.Value);// 设置输入类型参数
1315                 }
1316             }
1317         }
1318     }
1319     /**
1320      * 得到存储过程参数执行结果
1321      *
1322      * @param cs
1323      * @param params
1324      * @throws SQLException
1325      */
1326     private   void getSqlParameter(CallableStatement cs,
1327             SqlParameter... params) throws SQLException {
1328         for (SqlParameter param : params) {
1329             if (param.OutPut) {
1330                 String paramName = param.Name;
1331                 if (paramName == null || paramName.equals("")) {
1332                     param.Value = cs.getObject(1);// 返回类型参数值
1333                 } else {
1334                     param.Value = cs.getObject(paramName);// 输出类型参数值
1335                 }
1336             }
1337         }
1338     }
1339 
1340 	/**
1341 	 *
1342 	 * @Title: executeUpdate  by statement
1343 	 * @Description: (更新结果集)  1344 	 * @param @param sql
1345 	 * @param @return
1346 	 * @param @throws SQLException    设定文件  1347 	 * @return int    返回类型  1348 	 * @throws  1349 	 */
1350 	@SuppressWarnings("null")
1351 	public int executeUpdate(String sql) {
1352 		Statement statement = null;
1353 		Connection connection = null;
1354 		int result = 0;
1355 		try {
1356 			connection = getStatement();
1357 			result = statement.executeUpdate(sql);
1358 			connection.commit();//JDBC 事务管理
1359 		} catch (Exception e) {
1360 			e.printStackTrace();
1361 			try {
1362 				connection.rollback();//JDBC 事务管理
1363 			} catch (SQLException e1) {
1364 				e1.printStackTrace();
1365 			}
1366 		} finally {
1367 			try {
1368 				statement.close();
1369 				connection.close();
1370 			} catch (SQLException e) {
1371 				e.printStackTrace();
1372 			}
1373 
1374 		}
1375 		return result;
1376 	}
1377 
1378 
1379 
1380 
1381 
1382 	//-----------------------资源关闭---------------------------------------------
1383 	/**
1384 	 * 关闭所有资源
1385 	 *
1386 	 * @param statement
1387 	 */
1388 	private void closeAll(Connection connection,
1389 			PreparedStatement preparedStatement,
1390 			CallableStatement callableStatement, ResultSet resultSet) {
1391 		// 关闭结果集对象
1392 		if (resultSet != null) {
1393 			try {
1394 				resultSet.close();
1395 			} catch (SQLException e) {
1396 				System.out.println(e.getMessage());
1397 			}
1398 		}
1399 
1400 		// 关闭PreparedStatement对象
1401 		if (preparedStatement != null) {
1402 			try {
1403 				preparedStatement.close();
1404 			} catch (SQLException e) {
1405 				System.out.println(e.getMessage());
1406 			}
1407 		}
1408 
1409 		// 关闭CallableStatement 对象
1410 		if (callableStatement != null) {
1411 			try {
1412 				callableStatement.close();
1413 			} catch (SQLException e) {
1414 				System.out.println(e.getMessage());
1415 			}
1416 		}
1417 
1418 		// 关闭Connection 对象
1419 		if (connection != null) {
1420 			try {
1421 				connection.close();
1422 			} catch (SQLException e) {
1423 				System.out.println(e.getMessage());
1424 			}
1425 		}
1426 	}
1427 
1428 	/**
1429 	 *
1430 	 * @Title: close  1431 	 * @Description: (关闭所有的连接)  1432 	 * @param @throws SQLException    设定文件  1433 	 * @return void    返回类型  1434 	 * @throws  1435 	 */
1436 	public void close(Connection connection, Statement statement,
1437 			ResultSet resultSet) {
1438 		try {
1439 			if (resultSet != null) {
1440 				resultSet.close();
1441 				resultSet = null;
1442 			}
1443 			if (statement != null) {
1444 				statement.close();
1445 				statement = null;
1446 			}
1447 			if (connection != null) {
1448 				connection.close();
1449 				connection = null;
1450 			}
1451 		} catch (Exception e) {
1452 			e.printStackTrace();
1453 		}
1454 	}
1455 	 /**
1456      * 关闭JDBC对象,释放资源。
1457      *
1458      * @param con
1459      *            连接对象
1460      * @param ps
1461      *            命令对象
1462      * @param rs
1463      *            结果集对象
1464      * @throws SQLException
1465      */
1466     private static void close3(Connection con, Statement ps, ResultSet rs) {
1467         try {
1468             rs.close();
1469             if (rs != null) {
1470 
1471                 rs = null;
1472             }
1473             if (ps != null) {
1474                 ps.close();
1475                 ps = null;
1476             }
1477             if (con != null) {
1478                 con.close();
1479                 con = null;
1480             }
1481         } catch (SQLException e) {
1482             //  Auto-generated catch block
1483             e.printStackTrace();
1484         }
1485     }
1486 
1487 	  //--------------------main 方法----------------------------------------------
1488 		/**
1489 		 * 测试 连接是否成功
1490 		 *
1491 		 * @param args
1492 		 */
1493 		public static void main(String[] args) {
1494 			getConnection();
1495 		}
1496 
1497 
1498 }
1499 

JdbcDaoImpl.java

  1 package com.jacezhu.dao.impl;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 import java.util.Map;
  6 
  7 import com.jacezhu.dao.JdbcBaseDao;
  8 import com.jacezhu.dao.JdbcDao;
  9 import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
 10 import com.jacezhu.framework.connectUtil.jdbcUtl.PageModel;
 11 import com.jacezhu.model.demo.vo.Demo;
 12 import com.jacezhu.service.demo.impl.DemoMapper;
 13 
 14 import org.springframework.beans.factory.annotation.Autowired;
 15 import org.springframework.stereotype.Repository;
 16 @Repository
 17 public class JdbcDaoImpl extends Object implements JdbcDao{
 18 	@Autowired
 19     private   JdbcBaseDaoImpl jdbcBaseUtil =new JdbcBaseDaoImpl();
 20 
 21 	public JdbcBaseDaoImpl getJdbcBaseUtil() {
 22 		return jdbcBaseUtil;
 23 	}
 24 	public void setJdbcBaseUtil(JdbcBaseDaoImpl jdbcBaseUtil) {
 25 		this.jdbcBaseUtil = jdbcBaseUtil;
 26 	}
 27 	/**
 28 	 *
 29 	* @Title: insert   30 	* @Description: (插入单挑数据)   31 	* @param @param sql 查询sql
 32 	* @param @param obj 参数数组
 33 	* @param @param isGenerateKey (true  false)
 34 	* @param @return    设定文件   35 	* @return boolean    返回类型   36 	* @throws   37 	 */
 38 	public boolean insert(String sql, Object[] obj){
 39 
 40 		return jdbcBaseUtil.update(sql, obj, false);
 41 	 }
 42 	/**
 43 	 *
 44 	* @author  刘军
 45 	* @date 2016-3-19 下午2:23:42   46 	* @version V1.0    47 	* @Title: insertLines   48 	* @Description: (新增)   49 	* @param @param sql
 50 	* @param @param obj
 51 	* @param @return    设定文件   52 	* @return int    返回类型   53 	* @throws   54 	 */
 55 	public int insertLines(String sql, Object[] obj){
 56 
 57 		return jdbcBaseUtil.executeUpdate(sql, obj);
 58 	 }
 59 	/**
 60 	 *
 61 	* @author  刘军
 62 	* @date 2016-3-19 下午2:05:19   63 	* @version V1.0    64 	* @Title: insert   65 	* @Description: (新增)   66 	* @param @param sql
 67 	* @param @param obj
 68 	* @param @return    设定文件   69 	* @return boolean    返回类型   70 	* @throws   71 	 */
 72 	public boolean insertByList(String sql, List<Object> obj){
 73 
 74 		return jdbcBaseUtil.updateByPreparedStatement(sql, obj);
 75 	 }
 76 
 77 	/**
 78 	 *
 79 	* @Title: delete   80 	* @Description: (删除单挑数据)   81 	* @param @param sql 删除sql
 82 	* @param @param obj 参数数组
 83 	* @param @param isGenerateKey (true  false)
 84 	* @param @return    设定文件   85 	* @return boolean    返回类型   86 	* @throws   87 	 */
 88 	public boolean delete(String sql, Object[] obj){
 89 
 90 		return jdbcBaseUtil.update(sql, obj, false);
 91 	 }
 92 	/**
 93 	 *
 94 	* @author  刘军
 95 	* @date 2016-3-19 下午2:19:20   96 	* @version V1.0    97 	* @Title: delete   98 	* @Description: (删除单挑数据)   99 	* @param @param sql
100 	* @param @param obj
101 	* @param @return    设定文件  102 	* @return boolean    返回类型  103 	* @throws  104 	 */
105 	public boolean delete(String sql,List<Object> obj){
106 
107 		return jdbcBaseUtil.updateByPreparedStatement(sql, obj);
108 	 }
109 
110 	 /**
111 	  *
112 	 * @Title: deleteALL  113 	 * @Description: (批量删除数据)  114 	 * @param @param sql
115 	 * @param @param obj
116 	 * @param @return    设定文件  117 	 * @return boolean    返回类型  118 	 * @throws  119 	  */
120 	public boolean deleteALL(String sql, Object[] obj){
121 		StringBuffer sbStr = new StringBuffer();
122 		for (int i = 0; i < obj.length; i++) {
123 			sbStr.append("?,");
124 		}
125 		String sqls =sql+"("+ sbStr.substring(0, sbStr.length() - 1) + ")";
126 		return jdbcBaseUtil.update(sqls, obj, false);
127 	 }
128 	/**
129 	 *
130 	* @author  刘军
131 	* @date 2016-3-19 下午2:20:56  132 	* @version V1.0   133 	* @Title: deleteALL  134 	* @Description: (删除 批量删除 )  135 	* @param @param sql
136 	* @param @param obj
137 	* @param @return    设定文件  138 	* @return boolean    返回类型  139 	* @throws  140 	 */
141 	public boolean deleteALL(String sql,List<Object> obj){
142 		StringBuffer sbStr = new StringBuffer();
143 		for (int i = 0; i < obj.size(); i++) {
144 			sbStr.append("?,");
145 		}
146 		String sqls =sql+"("+ sbStr.substring(0, sbStr.length() - 1) + ")";
147 		return jdbcBaseUtil.updateByPreparedStatement(sqls, obj);
148 	 }
149 	 /**
150 	  *
151 	 * @Title: update  152 	 * @Description: (更新单挑数据记录)  153 	 * @param @param sql
154 	 * @param @param obj
155 	 * @param @return    设定文件  156 	 * @return boolean    返回类型  157 	 * @throws  158 	  */
159 	public boolean update(String sql, Object[] obj){
160 
161 		return jdbcBaseUtil.update(sql, obj, false);
162 	 }
163 	/**
164 	 *
165 	* @author  刘军
166 	* @date 2016-3-19 下午2:21:45  167 	* @version V1.0   168 	* @Title: update  169 	* @Description: (修改 )  170 	* @param @param sql
171 	* @param @param obj
172 	* @param @return    设定文件  173 	* @return boolean    返回类型  174 	* @throws  175 	 */
176 	public boolean update(String sql, List<Object> obj){
177 
178 		return jdbcBaseUtil.updateByPreparedStatement(sql, obj);
179 	 }
180 	 /**
181 	  *
182 	 * @Title: queryFrist  183 	 * @Description: (查询出第一条数据记录)  184 	 * @param @param tale
185 	 * @param @param objParams
186 	 * @param @return    设定文件  187 	 * @return Object    返回类型  188 	 * @throws  189 	  */
190 	 public Object queryFrist(String tale,Object[] objParams,ObjectMapper mapper){
191 
192 		 String sql = "select * from "+tale+"";
193 			Object[] obj = objParams;
194 		   return (Object) query(sql, obj, mapper).get(0);
195 	 }
196 	 /**
197 	  *
198 	 * @author  刘军
199 	 * @date 2016-3-19 上午9:41:06  200 	 * @version V1.0   201 	 * @Title: find  202 	 * @Description: (查询一条记录 )  203 	 * @param @param sql
204 	 * @param @param obj
205 	 * @param @param mapper
206 	 * @param @return    设定文件  207 	 * @return Object    返回类型  208 	 * @throws  209 	  */
210 	 public	 Object find(String sql, Object[] obj, ObjectMapper mapper){
211 		return jdbcBaseUtil. find( sql,  obj,  mapper) ;
212 
213 	 }
214 
215 	 /**
216 	  *
217 	 * @author  刘军
218 	 * @date 2016-3-19 上午9:41:06  219 	 * @version V1.0   220 	 * @Title: find  221 	 * @Description: (查询一条记录 )  222 	 * @param @param sql
223 	 * @param @param obj
224 	 * @param @param mapper
225 	 * @param @return    设定文件  226 	 * @return Object    返回类型  227 	 * @throws  228 	  */
229 	 public Object find(String sql,List obj,ObjectMapper mapper){
230 
231 		 return jdbcBaseUtil. find( sql,  obj,  mapper) ;
232 	 }
233 	/**
234 	 *
235 	* @Title: query  236 	* @Description: ( 查询所有的数据记录;并以list 集合(或者:Object 对象)返回 )  237 	* @param @param sql
238 	* @param @param obj
239 	* @param @param mapper
240 	* @param @return    设定文件  241 	* @return List<? extends Object>    返回类型  242 	* @throws  243 	 */
244 	public List<? extends Object> query(String sql, Object[] obj,
245 			ObjectMapper mapper) {
246 
247 		 return jdbcBaseUtil.query(sql, obj, mapper);
248 	}
249 	/**
250 	 *
251 	* @author   liujun<1136808529@qq.coom>
252 	* @date 2016-5-12 下午1:55:08  253 	* @version V1.0   254 	* @Title: query  255 	* @Description: (
256 	 *查询所有的数据记录;并以list 集合(或者:Object 对象)返回
257 	 *)  258 	* @param @param sql
259 	* @param @param obj
260 	* @param @param mapper
261 	* @param @return    设定文件  262 	* @return List<? extends Object>    返回类型  263 	* @throws  264 	 */
265 	public List<? extends Object> query(String sql, List obj,
266 			ObjectMapper mapper) {
267 
268 		 return jdbcBaseUtil.query(sql, obj, mapper);
269 	}
270 	/**
271 	 *
272 	* @Title: CountNum  273 	* @Description: ( select count(*)from table 的总数据条数)
274 	* @param @param tableName (数据库表名)
275 	* @param @return    设定文件  276 	* @return int    返回类型  277 	* @throws  278 	 */
279 	public int CountNum (String tableName){
280 		return jdbcBaseUtil.returnTableCount(tableName);
281 	}
282 
283 	/**
284 	 *
285 	* @author   liujun<1136808529@qq.coom>
286 	* @date 2016-5-12 下午11:19:59  287 	* @version V1.0   288 	* @Title: Count  289 	* @Description: (
290 	 * 返回 统计count 数据的数量
291 	 *)  292 	* @param @param sql
293 	* @param @return    设定文件  294 	* @return int    返回类型  295 	* @throws  296 	 */
297 	public long  Count(String sql){
298 		return jdbcBaseUtil.Count(sql);
299 	};
300 	/**
301 	 *
302 	* @Title: queryPageNumber  303 	* @Description: (分页查询)  304 	* @param @param pageNo 第几页
305 	* @param @param pageSize  一页显示多少条数据
306 	* @param @param table  查询哪个表
307 	* 全表无条件查询
308 	*  {select * from ( tablea a,tableb b where a.id=b.id)limt numStrat,numStop}
309 	* 全表 带条件模糊查询:
310 	*SELECT * FROM  demo a ,demo b WHERE a.id=b.id AND  a.id LIKE "1%" LIMIT 0,15;
311 	* @param @return    设定文件  312 	* @return PageModel    返回类型  313 	* @throws  314 	 */
315 	public PageModel queryPageNumber(int pageNo, int pageSize,String table) {
316 		//oracle  分页
317 		//String sql="select * from (select j.*,rownum rn from (select * from "+table+") j where rownum<=?) where rn>?";
318 		//mysql  分页
319 		String sql="SELECT * FROM "+table+" LIMIT ?,?;";
320 		return  queryPageNumber( pageNo, pageSize, table, sql);
321 
322 	}
323 
324 
325 	@SuppressWarnings({ "rawtypes", "unchecked" })
326 	public PageModel queryPageNumber(int pageNo, int pageSize,String table,String sql) {
327 		int countTotal=CountNum(table);
328 		Object[] obj = {(pageNo - 1) * pageSize,  pageNo * pageSize};
329 		List<Demo> list = (List<Demo>) query(sql, obj,new DemoMapper());
330 		PageModel pagemodel = new PageModel();
331 		pagemodel.setPageNo(pageNo);
332 		pagemodel.setPageSize(pageSize);
333 		pagemodel.setList(list);
334 		pagemodel.setTotalRecords(countTotal);
335 		if(pageSize!=0){
336 		 pagemodel.setCountPageNo(countTotal/pageSize);
337 		}
338 		return pagemodel;
339 
340 	}
341 	/**
342 	 *
343 	 * @Title: findSimpleResult  获取最后一条(单条)记录
344 	 * @Description: (查询单条记录)  345 	 * @param @param sql
346 	 * @param @param params
347 	 * @param @return    设定文件  348 	 * @return Map<String,Object>    返回类型  349 	 * @throws  350 	 */
351 	public Map<String, Object> findSimpleResult(String sql, List<Object> params){
352 
353 		return jdbcBaseUtil.findSimpleResult(sql, params);
354 	}
355 	/**
356 	 *
357 	* @author  刘军
358 	* @date 2016-3-19 上午12:30:02  359 	* @version V1.0   360 	* @Title: findModeResult  查询多条记录
361 	* @Description: (查询多条记录)  362 	* @param @param sql
363 	* @param @param params
364 	* @param @return    设定文件  365 	* @return List<Map<String,Object>>    返回类型  366 	* @throws  367 	 */
368 	public List<Map<String, Object>> findModeResult(String sql,	List<Object> params){
369 		return jdbcBaseUtil.findModeResult(sql,params);
370 	}
371 	/**
372 	 *
373 	* @author  刘军
374 	* @date 2016-3-19 上午8:43:07  375 	* @version V1.0   376 	* @Title: executeQuerySingle  377 	* @Description: (SQL 查询将查询结果:一行一列)  378 	* @param @param sql
379 	* @param @param params
380 	* @param @return    设定文件  381 	* @return Object    返回类型  382 	* @throws  383 	 */
384 	public Object executeQuerySingle(String sql, Object[] params){
385 		return jdbcBaseUtil.executeQuerySingle(sql, params);
386 	}
387 
388 	/**
389 	 *
390 	* @author  刘军
391 	* @date 2016-3-19 上午9:08:05  392 	* @version V1.0   393 	* @Title: findSimpleRefResult  394 	* @Description: (通过反射机制查询单条记录)  395 	* @param @param sql
396 	* @param @param params
397 	* @param @param cls
398 	* @param @return    设定文件  399 	* @return T    返回类型  400 	* @throws  401 	 */
402 	public <T> T findSimpleRefResult(String sql, List<Object> params,Class<T> cls) {
403 
404 		//return  JdbcBaseUtil.findSimpleRefResult(sql,  params, cls);
405 		return null;
406 	}
407 	/**
408 	 *
409 	* @author  刘军
410 	* @date 2016-3-19 上午9:13:39  411 	* @version V1.0   412 	* @Title: findMoreRefResult  413 	* @Description: ( 通过反射机制查询多条记录)  414 	* @param @param sql
415 	* @param @param params
416 	* @param @param cls
417 	* @param @return    设定文件  418 	* @return List<T>    返回类型  419 	* @throws  420 	 */
421 	public <T> List<T> findMoreRefResult(String sql, List<Object> params,
422 			Class<T> cls) {
423 		return jdbcBaseUtil.findMoreRefResult(sql, params, cls);
424 	}
425 	/**
426 	 *
427 	* @author  刘军
428 	* @date 2016-3-19 上午11:03:06  429 	* @version V1.0   430 	* @Title: excuteQuery  431 	* @Description: (获取结果集,并将结果放在List中)  432 	* @param @param sql
433 	* @param @param params
434 	* @param @return    设定文件  435 	* @return List<Object>    返回类型  436 	* @throws  437 	 */
438 	public List<Object> excuteQuery(String sql, Object[] params){
439 		return jdbcBaseUtil.excuteQuery( sql,  params);
440 	}
441 	/**
442 	 *
443 	* @author  刘军
444 	* @date 2016-3-19 上午11:03:03  445 	* @version V1.0   446 	* @Title: executeQuery  447 	* @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,)  448 	* @param @param sql
449 	* @param @param parameters
450 	* @param @return    设定文件  451 	* @return ArrayList    返回类型  452 	* @throws  453 	 */
454 	public ArrayList executeQuery(String sql, String[] parameters){
455 		return jdbcBaseUtil.executeQuery( sql,  parameters);
456 	}
457 
458 	/**
459 	 *
460 	* @author   liujun<1136808529@qq.coom>
461 	* @date 2016-5-17 上午11:33:28  462 	* @version V1.0   463 	* @Title: getSeq  464 	* @Description:  (
465 	 *  获取sequence 序列号
466 	 *)  467 	* @param @param sequenceName
468 	* @param @return    设定文件  469 	* @return int    返回类型  470 	* @throws  471 	 */
472 	public int getSeq(String sequenceName){
473 		return jdbcBaseUtil.getSeq(sequenceName);
474 	}
475 }
476 

六:实例参考

控制层顶层:BaseController.java

  1 package com.jacezhu.controller.base;
  2 
  3 import java.text.SimpleDateFormat;
  4 import java.util.Date;
  5 
  6 import com.jacezhu.framework.utils.StringEscapeEditor;
  7 
  8 import org.springframework.beans.propertyeditors.CustomDateEditor;
  9 import org.springframework.stereotype.Controller;
 10 import org.springframework.web.bind.ServletRequestDataBinder;
 11 import org.springframework.web.bind.annotation.InitBinder;
 12 import org.springframework.web.bind.annotation.PathVariable;
 13 import org.springframework.web.bind.annotation.RequestMapping;
 14 
 15 @Controller
 16 @RequestMapping("/base")
 17 public class BaseController {
 18 
 19 	protected int page = 1;// 当前页
 20 	protected int rows = 10;// 每页显示记录数
 21 	protected String sort;// 排序字段
 22 	protected String order = "asc";// asc/desc
 23 
 24 	protected String ids;// 主键集合,逗号分割
 25 
 26 	@InitBinder
 27 	public void initBinder(ServletRequestDataBinder binder) {
 28 		/**
 29 		 * 自动转换日期类型的字段格式
 30 		 */
 31 		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
 32 
 33 		/**
 34 		 * 防止XSS攻击
 35 		 */
 36 		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
 37 	}
 38 
 39 	/**
 40 	 * 用户跳转JSP页面
 41 	 *
 42 	 * 此方法不考虑权限控制
 43 	 * produces = "text/html;charset=UTF-8"
 44 	 * @param folder
 45 	 *            路径
 46 	 * @param jspName
 47 	 *            JSP名称(不加后缀)
 48 	 * @return 指定JSP页面
 49 	 */
 50 	@RequestMapping("/{folder}/{jspName}")
 51 	public String redirectJsp(@PathVariable String folder, @PathVariable String jspName) {
 52 		return "/" + folder + "/" + jspName;
 53 	}
 54 
 55 }
 56 

控制层实现层:StudentinfoController.java

  1 package com.jacezhu.controller.businessCore.CustomerManagement;
  2 
  3 import javax.servlet.http.HttpServletRequest;
  4 
  5 import org.springframework.beans.BeanUtils;
  6 import org.springframework.beans.factory.annotation.Autowired;
  7 import org.springframework.stereotype.Controller;
  8 import org.springframework.web.bind.annotation.RequestMapping;
  9 import org.springframework.web.bind.annotation.ResponseBody;
 10 
 11 import com.jacezhu.controller.base.BaseController;
 12 import com.jacezhu.framework.utils.BeanUtil.dateUtils.DateUtils;
 13 import com.jacezhu.model.base.pageModel.Grid;
 14 import com.jacezhu.model.base.pageModel.Json;
 15 import com.jacezhu.model.base.pageModel.PageFilter;
 16 import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo;
 17 import com.jacezhu.model.businessCore.CustomerManagement.vo.StudentInfo;
 18 import com.jacezhu.service.businessCore.CustomerManagement.StudentinfoServiceI;
 19 /**
 20  *
 21 * @Title: StudentinfoController.java   22 * @Package com.jacezhu.controller.businessCore.CustomerManagement   23 * @Description: ( 客户管理:学生信息管理)   24 * @author  刘军
 25 * @date 2016-3-20 下午3:59:30   26 * @version V1.0    27  */
 28 @Controller
 29 @RequestMapping("/studentinfo")
 30 public class StudentinfoController extends BaseController{
 31 	@Autowired
 32 	private StudentinfoServiceI studentinfoServiceI;
 33 
 34 	@RequestMapping("/manager")
 35 	public String manager() {
 36 		return "/businessCore/customer/student";
 37 	}
 38     /**
 39      *
 40     * @author  刘军
 41     * @date 2016-3-20 下午10:56:25   42     * @version V1.0    43     * @Title: dataGrid   44     * @Description: (获取列表数据: )   45     * @param @param studentInfo
 46     * @param @param ph
 47     * @param @return    设定文件   48     * @return Grid    返回类型   49     * @throws   50      */
 51 	@RequestMapping("/dataGrid")
 52 	@ResponseBody
 53 	public Grid dataGrid(StudentInfo studentInfo, PageFilter ph) {
 54 		Grid grid = new Grid();
 55 		grid.setRows(studentinfoServiceI.dataGrid(studentInfo, ph));
 56 		grid.setTotal(studentinfoServiceI.count(studentInfo, ph));
 57 		return grid;
 58 	}
 59 	//------------start----学生签到管理:查询学生信息-------------------------------
 60 	 /**
 61 	  *
 62 	 * @author   liujun<1136808529@qq.coom>
 63 	 * @date 2016-5-11 下午5:27:42   64 	 * @version V1.0    65 	 * @Title: dataGridToReport   66 	 * @Description: (
 67 	  * 查询未签到的学生信息
 68 	  *)   69 	 * @param @param studentInfo
 70 	 * @param @param ph
 71 	 * @param @return    设定文件   72 	 * @return Grid    返回类型   73 	 * @throws   74 	  */
 75 	@RequestMapping("/dataGridToReport")
 76 	@ResponseBody
 77 	public Grid dataGridToReport(StudentInfo studentInfo, PageFilter ph) {
 78 		Grid grid = new Grid();
 79 		grid.setRows(studentinfoServiceI.dataGridToReport(studentInfo, ph));
 80 		grid.setTotal(studentinfoServiceI.countToReport(studentInfo, ph));
 81 		return grid;
 82 	}
 83 	/**
 84 	 *
 85 	* @author   liujun<1136808529@qq.coom>
 86 	* @date 2016-5-11 下午5:29:16   87 	* @version V1.0    88 	* @Title: dataGridIsReported   89 	* @Description: (
 90 	 * 已经签到的学生信息
 91 	 *)   92 	* @param @param studentInfo
 93 	* @param @param ph
 94 	* @param @return    设定文件   95 	* @return Grid    返回类型   96 	* @throws   97 	 */
 98 	@RequestMapping("/dataGridIsReported")
 99 	@ResponseBody
100 	public Grid dataGridIsReported(StudentInfo studentInfo, PageFilter ph) {
101 		Grid grid = new Grid();
102 		grid.setRows(studentinfoServiceI.dataGridIsReported(studentInfo, ph));
103 		grid.setTotal(studentinfoServiceI.countIsReported(studentInfo, ph));
104 		return grid;
105 	}
106 	//---------end-------学生签到管理:查询学生信息-------------------------------
107     /**
108      *
109     * @author  刘军
110     * @date 2016-3-20 下午11:01:23  111     * @version V1.0   112     * @Title: addPage  113     * @Description: (显示:添加页面)  114     * @param @return    设定文件  115     * @return String    返回类型  116     * @throws  117      */
118 	@RequestMapping("/addPage")
119 	public String addPage() {
120 		return "/businessCore/customer/studentInfoAdd";
121 	}
122 	@RequestMapping("/addStuInfo")
123 	@ResponseBody
124 	public Json add(StudentInfo studentInfo) {
125 		Json j = new Json();
126 		try {
127 			studentinfoServiceI.add(studentInfo);
128 			j.setSuccess(true);
129 			j.setMsg("添加成功!");
130 		} catch (Exception e) {
131 			j.setMsg(e.getMessage());
132 		}
133 		return j;
134 	}
135 
136 	@RequestMapping("/delete")
137 	@ResponseBody
138 	public Json delete(Long id) {
139 		Json j = new Json();
140 		try {
141 			studentinfoServiceI.delete(id);
142 			j.setMsg("删除成功!");
143 			j.setSuccess(true);
144 		} catch (Exception e) {
145 			j.setMsg(e.getMessage());
146 		}
147 		return j;
148 	}
149 
150 	@RequestMapping("/get")
151 	@ResponseBody
152 	public TStudentinfo get(Long id) {
153 		return studentinfoServiceI.get(id);
154 	}
155 	@RequestMapping("/editPage")
156 	public String editPage(HttpServletRequest request, Long id) {
157 		TStudentinfo studentInfo = studentinfoServiceI.get(id);
158 		request.setAttribute("studentInfo", studentInfo);
159 		return "/businessCore/customer/studentInfoEdit";
160 	}
161 
162 	@RequestMapping("/edit")
163 	@ResponseBody
164 	public Json edit(StudentInfo studentInfo ) {
165 		Json j = new Json();
166 		try {
167 		    TStudentinfo studentinfos=new TStudentinfo();
168 			BeanUtils.copyProperties(studentInfo, studentinfos);
169 			studentinfos.setStuapplyTime(DateUtils.formatDate(studentInfo.getStuapplyTime(),DateUtils.FORMAT_SHORT));
170 
171 			studentinfoServiceI.edit(studentinfos);
172 			j.setSuccess(true);
173 			j.setMsg("编辑成功!");
174 		} catch (Exception e) {
175 			j.setMsg(e.getMessage());
176 		}
177 		return j;
178 	}
179 	@RequestMapping("/viewPage")
180 	public String viewPage(HttpServletRequest request, Long id) {
181 		TStudentinfo studentInfo = studentinfoServiceI.get(id);
182 		request.setAttribute("studentInfo", studentInfo);
183 		return "/businessCore/customer/studentInfoView";
184 	}
185 
186 }
187 

服务层 StudentinfoServiceI.java

  1 package com.jacezhu.service.businessCore.CustomerManagement;
  2 
  3 import java.util.List;
  4 
  5 import com.jacezhu.model.base.pageModel.PageFilter;
  6 import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo;
  7 import com.jacezhu.model.businessCore.CustomerManagement.vo.StudentInfo;
  8 import com.jacezhu.model.businessCore.CustomerManagement.vo.VStudentinfo;
  9 
 10 public interface StudentinfoServiceI {
 11 
 12 	public List<TStudentinfo> dataGrid(StudentInfo studentInfo, PageFilter ph);
 13 	public Long count(StudentInfo studentInfo, PageFilter ph);
 14 	//---------学生签到管理 查询学生信息------------
 15 	 /**  查询 未签到的学生信息
 16 	  */
 17 	public List<VStudentinfo> dataGridToReport(StudentInfo studentInfo, PageFilter ph);
 18 	public Long countToReport(StudentInfo studentInfo, PageFilter ph);
 19 
 20 	 /**查询已经签到的学生信息
 21 	  */
 22 	public List<TStudentinfo> dataGridIsReported(StudentInfo studentInfo, PageFilter ph);
 23 	public Long countIsReported(StudentInfo studentInfo, PageFilter ph);
 24 	//----------------------
 25 	public void add(StudentInfo studentInfo);
 26 	public void delete(Long id);
 27 	public TStudentinfo get(Long id);
 28 	public void edit(TStudentinfo studentInfo);
 29 
 30 
 31 }
 32 

服务实现层:StudentinfoServiceImpl.java

  1 package com.jacezhu.service.businessCore.CustomerManagement.impl;
  2 
  3 import java.util.ArrayList;
  4 import java.util.Date;
  5 import java.util.HashMap;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import javax.servlet.http.HttpServletRequest;
 10 import javax.servlet.http.Httpssion;
 11 
 12 import com.jacezhu.dao.BaseDaoI;
 13 import com.jacezhu.dao.impl.JdbcDaoImpl;
 14 import com.jacezhu.framework.constant.GlobalConstant;
 15 import com.jacezhu.model.base.pageModel.PageFilter;
 16 import com.jacezhu.model.base.pageModel.SessionInfo;
 17 import com.jacezhu.model.businessCore.CustomerManagement.THisStudentinfo;
 18 import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo;
 19 import com.jacezhu.model.businessCore.CustomerManagement.mapper.TStudentInfoMapper;
 20 import com.jacezhu.model.businessCore.CustomerManagement.mapper.VStudentinfoMapper;
 21 import com.jacezhu.model.businessCore.CustomerManagement.vo.StudentInfo;
 22 import com.jacezhu.model.businessCore.CustomerManagement.vo.VStudentinfo;
 23 import com.jacezhu.service.businessCore.CustomerManagement.StudentinfoServiceI;
 24 
 25 import org.springframework.beans.BeanUtils;
 26 import org.springframework.beans.factory.annotation.Autowired;
 27 import org.springframework.stereotype.Service;
 28 @Service
 29 public class StudentinfoServiceImpl implements StudentinfoServiceI{
 30 	@Autowired
 31 	private BaseDaoI<TStudentinfo> tstudentInfoDao ;
 32 	@Autowired
 33 	private BaseDaoI<StudentInfo> studentInfoDao ;
 34 
 35 	@Autowired
 36 	private BaseDaoI<THisStudentinfo> hisStudentInfoDao ;
 37 	//----使用spring专属的方式获取session 
 38     @Autowired
 39     private HttpSession session;
 40     @Autowired
 41     private HttpServletRequest request;
 42     //引入 jsbc 
 43 	private JdbcDaoImpl  daoImpl=new JdbcDaoImpl() ;
 44 
 45 	public JdbcDaoImpl getDaoImpl() {
 46 		return daoImpl;
 47 	}
 48 
 49 	public void setDaoImpl(JdbcDaoImpl daoImpl) {
 50 		this.daoImpl = daoImpl;
 51 	}
 52      /**
 53       * datagrid 列表数据查询
 54       */
 55 	@Override
 56 	public List<TStudentinfo> dataGrid(StudentInfo studentInfo, PageFilter ph) {
 57 		List<TStudentinfo> ul = new ArrayList<TStudentinfo>();
 58 		Map<String, Object> params = new HashMap<String, Object>();
 59 		String hql = " from TStudentinfo t  ";
 60 		List<TStudentinfo> l = tstudentInfoDao.find(hql + whereHql(studentInfo, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
 61 		for (TStudentinfo t : l) {
 62 			TStudentinfo u = new TStudentinfo();
 63 			BeanUtils.copyProperties(t, u);
 64 			ul.add(u);
 65 		}
 66 		return ul;
 67 	}
 68 
 69 	@Override
 70 	public Long count(StudentInfo studentInfo, PageFilter ph) {
 71 		Map<String, Object> params = new HashMap<String, Object>();
 72 		String hql = " from TStudentinfo t ";
 73 		return tstudentInfoDao.count("select count(*) " + hql + whereHql(studentInfo, params), params);
 74 	}
 75 
 76 	/**
 77 	 *
 78 	* @author  刘军
 79 	* @date 2016-4-16 下午11:17:07   80 	* @version V1.0    81 	* @Title: whereHql   82 	* @Description: ( datagrid  拼接查询语句  )   83 	* @param @param studentInfo
 84 	* @param @param params
 85 	* @param @return    设定文件   86 	* @return String    返回类型   87 	* @throws   88 	 */
 89 	private String whereHql(StudentInfo studentInfo, Map<String, Object> params) {
 90 		String hql = "";
 91 		if (studentInfo != null) {
 92 			hql += " where 1=1 and stustatus=1  ";
 93 			if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
 94 				hql += " and t.stuname like :stuname";
 95 				params.put("stuname", "%%" + studentInfo.getStuname() + "%%");
 96 			}
 97 			if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
 98 				hql += " and t.stuenglishName like :stuenglishName";
 99 				params.put("stuenglishName", "%%" + studentInfo.getStuenglishName() + "%%");
100 			}
101 			if (studentInfo.getStuapplyTimeStart() != null) {
102 				hql += " and t.stuapplyTime >= :stuapplyTimeStart";
103 				params.put("stuapplyTimeStart", studentInfo.getStuapplyTimeStart());
104 			}
105 			if (studentInfo.getStuapplyTimeEnd() != null) {
106 				hql += " and t.stuapplyTime <= :stuapplyTimeEnd";
107 				params.put("stuapplyTimeEnd", studentInfo.getStuapplyTimeEnd());
108 			}
109 		}
110 		return hql;
111 	}
112 	/**
113 	 *
114 	* @author  刘军
115 	* @date 2016-4-16 下午11:18:25  116 	* @version V1.0   117 	* @Title: orderHql  118 	* @Description: (datagrid  拼接 排序)  119 	* @param @param ph
120 	* @param @return    设定文件  121 	* @return String    返回类型  122 	* @throws  123 	 */
124 	private String orderHql(PageFilter ph) {
125 		String orderString = "";
126 		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
127 			orderString = " order by t." + ph.getSort() + "" + ph.getOrder();
128 		}
129 		return orderString;
130 	}
131 	//----------------------学生签到管理:查询未签到学生信息-ToReport------------------------------
132 	@Override
133 	public List<VStudentinfo> dataGridToReport(StudentInfo studentInfo, PageFilter ph) {
134 	    List<VStudentinfo> listJdbc=getSql(studentInfo,ph);
135 		return listJdbc;
136 	}
137 
138 	@Override
139 	public Long countToReport(StudentInfo studentInfo, PageFilter ph) {
140 		List<Object> obj=new ArrayList<Object>();
141 		String sql = " select count(*) as counts from t_studentinfo ts where 1=1  ";
142 		//----------拼写:查询条件
143 		if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
144 			sql += " and ts.stuname like '%"+ studentInfo.getStuname()+"%'";
145 		}
146 		if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
147 			sql += " and ts.stuenglishName like '%" +studentInfo.getStuenglishName()+"%'";
148 		}
149 		if (studentInfo.getStuapplyTimeStart() != null) {
150 			sql += " and ts.stuapplyTime >= '"+studentInfo.getStuapplyTimeStart()+"'";
151 		}
152 		if (studentInfo.getStuapplyTimeEnd() != null) {
153 			sql += " and ts.stuapplyTime <= '"+studentInfo.getStuapplyTimeEnd()+"'";
154 		}
155 		return daoImpl.Count(sql);
156 	}
157 
158 	//------jdbc  查询
159 
160 	@SuppressWarnings("unchecked")
161 	private List<VStudentinfo> getSql(StudentInfo studentInfo, PageFilter ph){
162 		List<VStudentinfo> list=new ArrayList<VStudentinfo>();
163 		String sql= "   SELECT ts.stuid AS stuid ,"
164 			         +" ts.stuname AS stuname  ,"
165 			         +" ts.stuenglishName AS stuenglishName,"
166 			         +" ts.stusex AS stusex ,"
167 			         +" ds.value AS sexname,"
168 			         +" ts.stubrithday AS stubrithday,"
169 			         +" ts.stuschool AS stuschool ,"
170 			         +" ts.stugrade AS stugrade,"
171 			         +" ts.studepartment AS studepartment,"
172 			         +" dp.value AS studepartmentname ,"
173 			         +" ts.stuRegistration AS stuRegistration,"
174 			         +" tr.value AS registrationname,"
175 			         +" ts.stupickUp AS stupickUp,"
176 			         +" dpk.value AS pickUpName,"
177 			         +" ts.stuattention AS stuattention,"
178 			         +" ts.stuhobby AS stuhobby ,"
179 			         +" ts.stuavoidFood AS stuavoidFood,"
180 			         +" ts.stuallergySmptoms AS stuallergySmptoms,"
181 			         +" ts.stuacuteillness AS stuacuteillness,"
182 			         +" ts.stuotherInfo AS stuotherInfo,"
183 			         +" ts.prId AS prId,"
184 			         +" tp.prName AS prName,"
185 			         +" ts.stustatus AS stustatus,"
186 			         +" dst.value AS stustatusName ,"
187 			         +" ts.stuapplyTime AS stuapplyTime,"
188 			         +" ts.userid AS userid ,su.name AS userName,"
189 			         +" ts.druguse AS druguse "
190 			         +" FROM   t_studentinfo  ts ,   t_dic_sex ds ,  t_dic_partment dp,  t_dic_pickup dpk,"
191 			         +" t_dic_status dst,   t_dic_registration tr , sys_user su, t_parentsinfo tp "
192 			         +" WHERE ts.stusex =ds.id  AND  ts.studepartment=dp.id  AND  ts.stuRegistration=tr.id "
193 			         +" AND  ts.stupickUp=dpk.id  AND  ts.stustatus=dst.id  AND  ts.userid = su.id AND  ts.prId=tp.prId   "
194 			         +" AND  ts.stuid NOT IN (SELECT tre.stuid  FROM t_reportsorexit tre WHERE  tre.reportstime BETWEEN  TIMESTAMP(DATE(SYSDATE())) AND  TIMESTAMP(ADDDATE(DATE(SYSDATE()),1)) )  ";
195 		//------拼接查询条件
196 		List<Object> obj=new ArrayList<Object>();
197 		//----------拼写:查询条件
198 		if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
199 			sql += " and ts.stuname like ? ";
200 			obj.add( "%" + studentInfo.getStuname() + "%");
201 		}
202 		if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
203 			sql += " and ts.stuenglishName like ? ";
204 			obj.add(  "%" + studentInfo.getStuenglishName() + "%");
205 		}
206 		if (studentInfo.getStuapplyTimeStart() != null) {
207 			sql += " and ts.stuapplyTime >= ? ";
208 			obj.add(  studentInfo.getStuapplyTimeStart());
209 		}
210 		if (studentInfo.getStuapplyTimeEnd() != null) {
211 			sql += " and ts.stuapplyTime <= ?  ";
212 			obj.add(  studentInfo.getStuapplyTimeEnd());
213 		}
214 		//----------  order by
215 		if(ph.getSort()!= null && ph.getOrder()!=null){
216 			sql +=  "   order by ts." + ph.getSort() + "" + ph.getOrder();
217 		}
218 		//----------- limit 分页        
219 		sql += "   LIMIT "+((ph.getPage() - 1) * ph.getRows())+","+ ph.getPage() * ph.getRows() ;
220 
221 		list=(List<VStudentinfo>)daoImpl.query(sql , obj, new VStudentinfoMapper());
222 		return list;
223 	}
224 
225 
226 
227 	/**
228 	 *
229 	* @author  刘军
230 	* @date 2016-4-16 下午11:17:07  231 	* @version V1.0   232 	* @Title: whereHql  233 	* @Description: ( datagrid  拼接查询语句  )  234 	* @param @param studentInfo
235 	* @param @param params
236 	* @param @return    设定文件  237 	* @return String    返回类型  238 	* @throws  239 	 */
240 	private String whereHqlToReport(StudentInfo studentInfo, Map<String, Object> params) {
241 		String hql = "";
242 		if (studentInfo != null) {
243 			hql += " where 1=1 and t.stustatus=1  and t.stuid not in"
244 	     	+  " (select tr.stuid  from TReportsorexit tr  "
245 			+  "   WHERE  tr.reportstime BETWEEN  TIMESTAMP(DATE(SYSDATE())) AND  TIMESTAMP(ADDDATE(DATE(SYSDATE()),1)) )  ";
246 			if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
247 				hql += " and t.stuname like :stuname";
248 				params.put("stuname", "%%" + studentInfo.getStuname() + "%%");
249 			}
250 			if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
251 				hql += " and t.stuenglishName like :stuenglishName";
252 				params.put("stuenglishName", "%%" + studentInfo.getStuenglishName() + "%%");
253 			}
254 			if (studentInfo.getStuapplyTimeStart() != null) {
255 				hql += " and t.stuapplyTime >= :stuapplyTimeStart";
256 				params.put("stuapplyTimeStart", studentInfo.getStuapplyTimeStart());
257 			}
258 			if (studentInfo.getStuapplyTimeEnd() != null) {
259 				hql += " and t.stuapplyTime <= :stuapplyTimeEnd";
260 				params.put("stuapplyTimeEnd", studentInfo.getStuapplyTimeEnd());
261 			}
262 		}
263 		return hql;
264 	}
265 
266 
267 
268 
269 
270 
271 
272 	//-------------查询:已经签到的学生信息-----------------------------
273 
274 	@Override
275 	public List<TStudentinfo> dataGridIsReported(StudentInfo studentInfo, PageFilter ph) {
276 		Map<String, Object> params = new HashMap<String, Object>();
277 		String hql = " from TStudentinfo t  ";
278 		List<TStudentinfo> l = tstudentInfoDao.find(hql + whereHqlIsReported(studentInfo, params) + orderHqlIsReported(ph), params, ph.getPage(), ph.getRows());
279 
280 		return l;
281 	}
282 
283 
284 
285 	@Override
286 	public Long countIsReported(StudentInfo studentInfo, PageFilter ph) {
287 		Map<String, Object> params = new HashMap<String, Object>();
288 		String hql = " from TStudentinfo t ";
289 		return tstudentInfoDao.count("select count(*) " + hql + whereHqlToReport(studentInfo, params), params);
290 	}
291 
292 	/**
293 	 *
294 	* @author  刘军
295 	* @date 2016-4-16 下午11:17:07  296 	* @version V1.0   297 	* @Title: whereHql  298 	* @Description: ( datagrid  拼接查询语句  )  299 	* @param @param studentInfo
300 	* @param @param params
301 	* @param @return    设定文件  302 	* @return String    返回类型  303 	* @throws  304 	 */
305 	private String whereHqlIsReported(StudentInfo studentInfo, Map<String, Object> params) {
306 		String hql = "";
307 		if (studentInfo != null) {
308 			hql += " where 1=1 and t.stustatus=1  and t.stuid  in"
309 	     	+  " (select tr.stuid  from TReportsorexit tr  "
310 			+  "   WHERE  tr.reportstime BETWEEN  TIMESTAMP(DATE(SYSDATE())) AND  TIMESTAMP(ADDDATE(DATE(SYSDATE()),1)) )  ";
311 			if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
312 				hql += " and t.stuname like :stuname";
313 				params.put("stuname", "%%" + studentInfo.getStuname() + "%%");
314 			}
315 			if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
316 				hql += " and t.stuenglishName like :stuenglishName";
317 				params.put("stuenglishName", "%%" + studentInfo.getStuenglishName() + "%%");
318 			}
319 			if (studentInfo.getStuapplyTimeStart() != null) {
320 				hql += " and t.stuapplyTime >= :stuapplyTimeStart";
321 				params.put("stuapplyTimeStart", studentInfo.getStuapplyTimeStart());
322 			}
323 			if (studentInfo.getStuapplyTimeEnd() != null) {
324 				hql += " and t.stuapplyTime <= :stuapplyTimeEnd";
325 				params.put("stuapplyTimeEnd", studentInfo.getStuapplyTimeEnd());
326 			}
327 		}
328 		return hql;
329 	}
330 
331 	/**
332 	 *
333 	* @author  刘军
334 	* @date 2016-4-16 下午11:18:25  335 	* @version V1.0   336 	* @Title: orderHql  337 	* @Description: (datagrid  拼接 排序)  338 	* @param @param ph
339 	* @param @return    设定文件  340 	* @return String    返回类型  341 	* @throws  342 	 */
343 	private String orderHqlIsReported(PageFilter ph) {
344 		String orderString = "";
345 		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
346 			orderString = " order by t." + ph.getSort() + "" + ph.getOrder();
347 		}
348 		return orderString;
349 	}
350 
351 	//-------------------------------------------------------------------------
352 
353     /**
354      * 添加学生信息
355      */
356 	@Override
357 	public void add(StudentInfo studentInfo) {
358 		TStudentinfo tStudentinfo = new TStudentinfo();
359 		BeanUtils.copyProperties(studentInfo, tStudentinfo);
360 		tStudentinfo.setStuapplyTime(new Date());//创建时间
361 		tStudentinfo.setStustatus(1);//有效状态
362 		tStudentinfo.setStudayCost( studentInfo.getStudayCost() );
363 		tstudentInfoDao.save(tStudentinfo);
364 	}
365 	/**
366 	 *
367 	* @author  刘军
368 	* @date 2016-4-16 下午11:18:25  369 	* @version V1.0   370 	* @Title: orderHql  371 	* @Description: ( 删除学生信息)  372 	* @param @param ph
373 	* @param @return    设定文件  374 	* @return String    返回类型  375 	* @throws  376 	 */
377 	@Override
378 	public void delete(Long id) {
379 		TStudentinfo studentInfo = tstudentInfoDao.get(TStudentinfo.class, id);
380 		studentInfo.setStustatus(0);//置为无效状态
381 		//获取登陆 用户信息
382 		SessionInfo sessionInfo=(SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO);
383 		THisStudentinfo hisStudentinfo=new THisStudentinfo() ;
384 		BeanUtils.copyProperties(studentInfo, hisStudentinfo);
385 		//保存:修改用户信息的操作员信息
386 		hisStudentinfo.setUpdateTime(new Date());
387 		hisStudentinfo.setUpdateUserId(Integer.parseInt((sessionInfo.getId()+"").trim()));
388 		hisStudentinfo.setActionMethod("delete");
389 		//保存历史表信息
390 	    hisStudentInfoDao.save(hisStudentinfo);
391 
392 	  //跟新数据
393 	  	tstudentInfoDao.update(studentInfo);
394 	}
395 	/**
396 	 *
397 	* @author  刘军
398 	* @date 2016-4-16 下午11:18:25  399 	* @version V1.0   400 	* @Title: orderHql  401 	* @Description: ( 根据学生id  获取学生信息)  402 	* @param @param ph
403 	* @param @return    设定文件  404 	* @return String    返回类型  405 	* @throws  406 	 */
407 	@Override
408 	public TStudentinfo get(Long id) {
409 		TStudentinfo studentInfo  = tstudentInfoDao.get(TStudentinfo.class, id);
410 		return studentInfo;
411 	}
412 	/**
413 	 *
414 	* @author  刘军
415 	* @date 2016-4-16 下午11:18:25  416 	* @version V1.0   417 	* @Title: orderHql  418 	* @Description: ( 修改 学生信息 )  419 	* @param @param ph
420 	* @param @return    设定文件  421 	* @return String    返回类型  422 	* @throws  423 	 */
424 	@Override
425 	public void edit(TStudentinfo studentInfo) {
426 
427 		//获取登陆 用户信息
428 		SessionInfo sessionInfo=(SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO);
429 
430 		THisStudentinfo hisStudentinfo=new THisStudentinfo() ;
431 		TStudentinfo studentinfo2=queryfirst((long)studentInfo.getStuid()) ;//get((long)studentInfo.getUserid());
432 		BeanUtils.copyProperties(studentinfo2, hisStudentinfo);
433 
434 		//保存:修改用户信息的操作员信息
435 		hisStudentinfo.setUpdateTime(new Date());
436 		hisStudentinfo.setUpdateUserId(Integer.parseInt((sessionInfo.getId()+"").trim()));
437 		hisStudentinfo.setActionMethod("update");
438 		//保存历史表信息
439 	    hisStudentInfoDao.save(hisStudentinfo);
440 
441 		//跟新数据
442 		tstudentInfoDao.update(studentInfo);
443 	}
444 	   /**
445      * 查询第一条数据
446      */
447 	public TStudentinfo queryfirst(Long stuid) {
448 		String sql = "select * from  t_studentinfo where stuid= ?";
449 		Object[] obj = {stuid};
450 		return (TStudentinfo) daoImpl.find(sql, obj, new TStudentInfoMapper()) ;
451 	}
452 }
453 

JavaBean 层:TStudentinfo.java

  1 package com.jacezhu.model.businessCore.CustomerManagement;
  2 
  3 import java.util.Date;
  4 
  5 import javax.persistence.Column;
  6 import javax.persistence.Entity;
  7 import javax.persistence.GeneratedValue;
  8 import static javax.persistence.GenerationType.IDENTITY;
  9 import javax.persistence.Id;
 10 import javax.persistence.Table;
 11 
 12 /**
 13  * TStudentinfo entity. @author MyEclipse Persistence Tools
 14  * 学生信息注册管理
 15  */
 16 @Entity
 17 @Table(name = "t_studentinfo", catalog = "xlzj_sh")
 18 public class TStudentinfo implements java.io.Serializable {
 19 
 20 	// Fields
 21 
 22 	private Long stuid;//学生信息表主键  id
 23 	private String stuname;//学生名字
 24 	private String stuenglishName;//学生英文名
 25 	private Integer stusex;//学生性别  dic: 0 ;男 1 女
 26 	private String stubrithday;//学生生日
 27 	private String stuschool;//学生就读于那个学校
 28 	private String stugrade;//学生是几年级的
 29 	private Integer studepartment;//中/英文部	dic: 1   中文部   2英文部
 30 	private String stuRegistration;//报名方式  dic: 0 :晚托班 1:1对1辅导 2:上门家教服务 3:其他
 31 	private Integer stupickUp;//是否接送  dic: 1 接送 ;0 :不接送
 32 	private String stuattention;//注意事项
 33 	private String stuhobby;//兴趣爱好
 34 	private String stuavoidFood;//忌口食物
 35 	private String stuallergySmptoms;//过敏症状
 36 	private String stuacuteillness;//急性病史
 37 	private String stuotherInfo;//其他信息
 38 	private Long prId;//家长信息表主键
 39 	private Integer stustatus;//学生有效状态  dic: 0 无效 1:有效
 40 	private Date stuapplyTime;//注册时间
 41 	private Integer userid;//注册人id
 42 	private String druguse;//drug use  药物使用
 43 	private String stuschoolTech;// 学生在学校的负责老师姓名
 44 	private String stuschoolTechTel;//学生在校的负责老师的联系电话
 45 	private String startStudayDate;//课程服务的起始时间
 46 	private String endStudayDate;//课程服务的终止时间
 47  	private String studayCost;//学费
 48 
 49 
 50 	// Constructors
 51 
 52 	/** default constructor */
 53 	public TStudentinfo() {
 54 	}
 55 
 56 	/** full constructor */
 57 	public TStudentinfo(String stuname, String stuenglishName, Integer stusex,
 58 			String stubrithday, String stuschool, String stugrade,
 59 			Integer studepartment, String stuRegistration, Integer stupickUp,
 60 			String stuattention, String stuhobby, String stuavoidFood,
 61 			String stuallergySmptoms, String stuacuteillness,
 62 			String stuotherInfo, Long prId, Integer stustatus,
 63 			Date stuapplyTime, Integer userid, String druguse ,String stuschoolTech, String stuschoolTechTel,
 64 			String startStudayDate , String endStudayDate , String studayCost) {
 65 		this.stuname = stuname;
 66 		this.stuenglishName = stuenglishName;
 67 		this.stusex = stusex;
 68 		this.stubrithday = stubrithday;
 69 		this.stuschool = stuschool;
 70 		this.stugrade = stugrade;
 71 		this.studepartment = studepartment;
 72 		this.stuRegistration = stuRegistration;
 73 		this.stupickUp = stupickUp;
 74 		this.stuattention = stuattention;
 75 		this.stuhobby = stuhobby;
 76 		this.stuavoidFood = stuavoidFood;
 77 		this.stuallergySmptoms = stuallergySmptoms;
 78 		this.stuacuteillness = stuacuteillness;
 79 		this.stuotherInfo = stuotherInfo;
 80 		this.prId = prId;
 81 		this.stustatus = stustatus;
 82 		this.stuapplyTime = stuapplyTime;
 83 		this.userid = userid;
 84 		this.druguse = druguse;
 85 		this.stuschoolTech = stuschoolTech;
 86 		this.stuschoolTechTel = stuschoolTechTel;
 87 		this.startStudayDate = startStudayDate;
 88 		 this.endStudayDate = endStudayDate;
 89 		this.studayCost = studayCost;
 90 	}
 91 
 92 	// Property accessors
 93 	@Id
 94 	@GeneratedValue(strategy = IDENTITY)
 95 	@Column(name = "stuid", unique = true, nullable = false)
 96 	public Long getStuid() {
 97 		return this.stuid;
 98 	}
 99 
100 	public void setStuid(Long stuid) {
101 		this.stuid = stuid;
102 	}
103 
104 	@Column(name = "stuname", length = 50)
105 	public String getStuname() {
106 		return this.stuname;
107 	}
108 
109 	public void setStuname(String stuname) {
110 		this.stuname = stuname;
111 	}
112 
113 	@Column(name = "stuenglishName", length = 50)
114 	public String getStuenglishName() {
115 		return this.stuenglishName;
116 	}
117 
118 	public void setStuenglishName(String stuenglishName) {
119 		this.stuenglishName = stuenglishName;
120 	}
121 
122 	@Column(name = "stusex", length = 1)
123 	public Integer getStusex() {
124 		return this.stusex;
125 	}
126 
127 	public void setStusex(Integer stusex) {
128 		this.stusex = stusex;
129 	}
130 
131 	@Column(name = "stubrithday", length = 10)
132 	public String getStubrithday() {
133 		return this.stubrithday;
134 	}
135 
136 	public void setStubrithday(String stubrithday) {
137 		this.stubrithday = stubrithday;
138 	}
139 
140 	@Column(name = "stuschool", length = 100)
141 	public String getStuschool() {
142 		return this.stuschool;
143 	}
144 
145 	public void setStuschool(String stuschool) {
146 		this.stuschool = stuschool;
147 	}
148 
149 	@Column(name = "stugrade", length = 10)
150 	public String getStugrade() {
151 		return this.stugrade;
152 	}
153 
154 	public void setStugrade(String stugrade) {
155 		this.stugrade = stugrade;
156 	}
157 
158 	@Column(name = "studepartment", length = 1)
159 	public Integer getStudepartment() {
160 		return this.studepartment;
161 	}
162 
163 	public void setStudepartment(Integer studepartment) {
164 		this.studepartment = studepartment;
165 	}
166 
167 	@Column(name = "stuRegistration", length = 1)
168 	public String getStuRegistration() {
169 		return this.stuRegistration;
170 	}
171 
172 	public void setStuRegistration(String stuRegistration) {
173 		this.stuRegistration = stuRegistration;
174 	}
175 
176 	@Column(name = "stupickUp", length = 1)
177 	public Integer getStupickUp() {
178 		return this.stupickUp;
179 	}
180 
181 	public void setStupickUp(Integer stupickUp) {
182 		this.stupickUp = stupickUp;
183 	}
184 
185 	@Column(name = "stuattention", length = 500)
186 	public String getStuattention() {
187 		return this.stuattention;
188 	}
189 
190 	public void setStuattention(String stuattention) {
191 		this.stuattention = stuattention;
192 	}
193 
194 	@Column(name = "stuhobby", length = 200)
195 	public String getStuhobby() {
196 		return this.stuhobby;
197 	}
198 
199 	public void setStuhobby(String stuhobby) {
200 		this.stuhobby = stuhobby;
201 	}
202 
203 	@Column(name = "stuavoidFood", length = 200)
204 	public String getStuavoidFood() {
205 		return this.stuavoidFood;
206 	}
207 
208 	public void setStuavoidFood(String stuavoidFood) {
209 		this.stuavoidFood = stuavoidFood;
210 	}
211 
212 	@Column(name = "stuallergySmptoms", length = 500)
213 	public String getStuallergySmptoms() {
214 		return this.stuallergySmptoms;
215 	}
216 
217 	public void setStuallergySmptoms(String stuallergySmptoms) {
218 		this.stuallergySmptoms = stuallergySmptoms;
219 	}
220 
221 	@Column(name = "stuacuteillness", length = 500)
222 	public String getStuacuteillness() {
223 		return this.stuacuteillness;
224 	}
225 
226 	public void setStuacuteillness(String stuacuteillness) {
227 		this.stuacuteillness = stuacuteillness;
228 	}
229 
230 	@Column(name = "stuotherInfo", length = 500)
231 	public String getStuotherInfo() {
232 		return this.stuotherInfo;
233 	}
234 
235 	public void setStuotherInfo(String stuotherInfo) {
236 		this.stuotherInfo = stuotherInfo;
237 	}
238 
239 	@Column(name = "prId")
240 	public Long getPrId() {
241 		return this.prId;
242 	}
243 
244 	public void setPrId(Long prId) {
245 		this.prId = prId;
246 	}
247 
248 	@Column(name = "stustatus", length = 1)
249 	public Integer getStustatus() {
250 		return this.stustatus;
251 	}
252 
253 	public void setStustatus(Integer stustatus) {
254 		this.stustatus = stustatus;
255 	}
256 
257 	@Column(name = "stuapplyTime" )
258 	public Date getStuapplyTime() {
259 		return this.stuapplyTime;
260 	}
261 
262 	public void setStuapplyTime(Date stuapplyTime) {
263 		this.stuapplyTime = stuapplyTime;
264 	}
265 
266 	@Column(name = "userid")
267 	public Integer getUserid() {
268 		return this.userid;
269 	}
270 
271 	public void setUserid(Integer userid) {
272 		this.userid = userid;
273 	}
274 
275 	@Column(name = "druguse", length = 500)
276 	public String getDruguse() {
277 		return this.druguse;
278 	}
279 
280 	public void setDruguse(String druguse) {
281 		this.druguse = druguse;
282 	}
283 
284 	@Column(name = "stuschool_tech", length = 100)
285 	public String getStuschoolTech() {
286 		return this.stuschoolTech;
287 	}
288 
289 	public void setStuschoolTech(String stuschoolTech) {
290 		this.stuschoolTech = stuschoolTech;
291 	}
292 
293 	@Column(name = "stuschool_tech_tel", length = 20)
294 	public String getStuschoolTechTel() {
295 		return this.stuschoolTechTel;
296 	}
297 
298 	public void setStuschoolTechTel(String stuschoolTechTel) {
299 		this.stuschoolTechTel = stuschoolTechTel;
300 	}
301 
302 	@Column(name = "start_studay_date", length = 19)
303 	public String getStartStudayDate() {
304 		return this.startStudayDate;
305 	}
306 
307 	public void setStartStudayDate(String startStudayDate) {
308 		this.startStudayDate = startStudayDate;
309 	}
310 
311 	 @Column(name = "end_studay_date", length = 19)
312 	public String getEndStudayDate() {
313 		return this.endStudayDate;
314 	}
315 
316 	public void setEndStudayDate(String endStudayDate) {
317 		this.endStudayDate = endStudayDate;
318 	}
319 
320 	@Column(name = "studay_cost", precision = 16, scale = 0)
321 	public String getStudayCost() {
322 		return this.studayCost;
323 	}
324 
325 	public void setStudayCost(String studayCost) {
326 		this.studayCost = studayCost;
327 	}
328 }

JavaBean 参数对象:StudentInfo.java

  1 package com.jacezhu.model.businessCore.CustomerManagement.vo;
  2 import java.util.Date;
  3 /**
  4  *
  5 * @Title: StudentInfo.java    6 * @Package com.jacezhu.pageModel.businessCore.CustomerManagement    7 * @Description: (
  8 * beanVo  用于接收查询条件 的参数
  9 * )   10 * @author   liujun<1136808529@qq.coom>
 11 * @date 2016-4-24 下午12:11:17   12 * @version V1.0    13  */
 14 public class StudentInfo implements java.io.Serializable {
 15 
 16 	// Fields
 17 
 18 	/**   19 	* @Fields serialVersionUID : (用一句话描述这个变量表示什么)   20 	*/
 21 	private static final long serialVersionUID = 1L;
 22 	private Long stuid;//学生信息表主键  id
 23 	private String stuname;//学生名字
 24 	private String stuenglishName;//学生英文名
 25 	private Integer stusex;//学生性别  dic: 0 ;男 1 女
 26 	private String stubrithday;//学生生日
 27 	private String stuschool;//学生就读于那个学校
 28 	private String stugrade;//学生是几年级的
 29 	private Integer studepartment;//中/英文部	dic: 1   中文部   2英文部
 30 	private String stuRegistration;//报名方式  dic: 0 :晚托班 1:1对1辅导 2:上门家教服务 3:其他
 31 	private Integer stupickUp;//是否接送  dic: 1 接送 ;0 :不接送
 32 	private String stuattention;//注意事项
 33 	private String stuhobby;//兴趣爱好
 34 	private String stuavoidFood;//忌口食物
 35 	private String stuallergySmptoms;//过敏症状
 36 	private String stuacuteillness;//急性病史
 37 	private String stuotherInfo;//其他信息
 38 	private Long prId;//家长信息表主键
 39 	private Integer stustatus;//学生有效状态  dic: 0 无效 1:有效
 40 	private String stuapplyTime;//注册时间
 41 	private Integer userid;//注册人id
 42 	private String druguse;//drug use  药物使用
 43 	private Date  stuapplyTimeStart;
 44 	private Date  stuapplyTimeEnd;
 45 	private String stuschoolTech;// 学生在学校的负责老师姓名
 46 	private String stuschoolTechTel;//学生在校的负责老师的联系电话
 47 	private String startStudayDate;//课程服务的起始时间
 48 	private String endStudayDate;//课程服务的终止时间
 49 	private String studayCost;//学费
 50 
 51 
 52 	public Date getStuapplyTimeStart() {
 53 		return stuapplyTimeStart;
 54 	}
 55 	public void setStuapplyTimeStart(Date stuapplyTimeStart) {
 56 		this.stuapplyTimeStart = stuapplyTimeStart;
 57 	}
 58 	public Date getStuapplyTimeEnd() {
 59 		return stuapplyTimeEnd;
 60 	}
 61 	public void setStuapplyTimeEnd(Date stuapplyTimeEnd) {
 62 		this.stuapplyTimeEnd = stuapplyTimeEnd;
 63 	}
 64 	public Long getStuid() {
 65 		return stuid;
 66 	}
 67 	public void setStuid(Long stuid) {
 68 		this.stuid = stuid;
 69 	}
 70 	public String getStuname() {
 71 		return stuname;
 72 	}
 73 	public void setStuname(String stuname) {
 74 		this.stuname = stuname;
 75 	}
 76 	public String getStuenglishName() {
 77 		return stuenglishName;
 78 	}
 79 	public void setStuenglishName(String stuenglishName) {
 80 		this.stuenglishName = stuenglishName;
 81 	}
 82 	public Integer getStusex() {
 83 		return stusex;
 84 	}
 85 	public void setStusex(Integer stusex) {
 86 		this.stusex = stusex;
 87 	}
 88 	public String getStubrithday() {
 89 		return stubrithday;
 90 	}
 91 	public void setStubrithday(String stubrithday) {
 92 		this.stubrithday = stubrithday;
 93 	}
 94 	public String getStuschool() {
 95 		return stuschool;
 96 	}
 97 	public void setStuschool(String stuschool) {
 98 		this.stuschool = stuschool;
 99 	}
100 	public String getStugrade() {
101 		return stugrade;
102 	}
103 	public void setStugrade(String stugrade) {
104 		this.stugrade = stugrade;
105 	}
106 	public Integer getStudepartment() {
107 		return studepartment;
108 	}
109 	public void setStudepartment(Integer studepartment) {
110 		this.studepartment = studepartment;
111 	}
112 	public String getStuRegistration() {
113 		return stuRegistration;
114 	}
115 	public void setStuRegistration(String stuRegistration) {
116 		this.stuRegistration = stuRegistration;
117 	}
118 	public Integer getStupickUp() {
119 		return stupickUp;
120 	}
121 	public void setStupickUp(Integer stupickUp) {
122 		this.stupickUp = stupickUp;
123 	}
124 	public String getStuattention() {
125 		return stuattention;
126 	}
127 	public void setStuattention(String stuattention) {
128 		this.stuattention = stuattention;
129 	}
130 	public String getStuhobby() {
131 		return stuhobby;
132 	}
133 	public void setStuhobby(String stuhobby) {
134 		this.stuhobby = stuhobby;
135 	}
136 	public String getStuavoidFood() {
137 		return stuavoidFood;
138 	}
139 	public void setStuavoidFood(String stuavoidFood) {
140 		this.stuavoidFood = stuavoidFood;
141 	}
142 	public String getStuallergySmptoms() {
143 		return stuallergySmptoms;
144 	}
145 	public void setStuallergySmptoms(String stuallergySmptoms) {
146 		this.stuallergySmptoms = stuallergySmptoms;
147 	}
148 	public String getStuacuteillness() {
149 		return stuacuteillness;
150 	}
151 	public void setStuacuteillness(String stuacuteillness) {
152 		this.stuacuteillness = stuacuteillness;
153 	}
154 	public String getStuotherInfo() {
155 		return stuotherInfo;
156 	}
157 	public void setStuotherInfo(String stuotherInfo) {
158 		this.stuotherInfo = stuotherInfo;
159 	}
160 	public Long getPrId() {
161 		return prId;
162 	}
163 	public void setPrId(Long prId) {
164 		this.prId = prId;
165 	}
166 	public Integer getStustatus() {
167 		return stustatus;
168 	}
169 	public void setStustatus(Integer stustatus) {
170 		this.stustatus = stustatus;
171 	}
172 	public String getStuapplyTime() {
173 		return stuapplyTime;
174 	}
175 	public void setStuapplyTime(String stuapplyTime) {
176 		this.stuapplyTime = stuapplyTime;
177 	}
178 	public Integer getUserid() {
179 		return userid;
180 	}
181 	public void setUserid(Integer userid) {
182 		this.userid = userid;
183 	}
184 	public String getDruguse() {
185 		return druguse;
186 	}
187 	public void setDruguse(String druguse) {
188 		this.druguse = druguse;
189 	}
190 	public String getStuschoolTech() {
191 		return stuschoolTech;
192 	}
193 	public void setStuschoolTech(String stuschoolTech) {
194 		this.stuschoolTech = stuschoolTech;
195 	}
196 	public String getStuschoolTechTel() {
197 		return stuschoolTechTel;
198 	}
199 	public void setStuschoolTechTel(String stuschoolTechTel) {
200 		this.stuschoolTechTel = stuschoolTechTel;
201 	}
202 	public String getStartStudayDate() {
203 		return startStudayDate;
204 	}
205 	public void setStartStudayDate(String startStudayDate) {
206 		this.startStudayDate = startStudayDate;
207 	}
208 	public String getEndStudayDate() {
209 		return endStudayDate;
210 	}
211 	public void setEndStudayDate(String endStudayDate) {
212 		this.endStudayDate = endStudayDate;
213 	}
214 	public String getStudayCost() {
215 		return studayCost;
216 	}
217 	public void setStudayCost(String studayCost) {
218 		this.studayCost = studayCost;
219 	}
220 
221 
222 }

JavaBean 与表字段的取值对于关系对象:TStudentInfoMapper.java

  1 
  2 
  3 package com.jacezhu.model.businessCore.CustomerManagement.mapper;
  4 
  5 import java.sql.ResultSet;
  6 
  7 import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
  8 import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo;
  9 
 10 //
 11 public class TStudentInfoMapper  implements ObjectMapper {
 12 
 13 	@Override
 14 	public Object mapping(ResultSet rs) {
 15 		TStudentinfo d=new TStudentinfo();
 16 		try{
 17 
 18 			d.setStuid(rs.getLong("stuid"));//学生信息表主键  id
 19 			d.setStuname(rs.getString("stuname"));//学生名字
 20 			d.setStuenglishName( rs.getString("stuenglishName") );//学生英文名
 21 			d.setStusex( rs.getInt("stusex") ); //学生性别  dic: 0 ;男 1 女
 22 			d.setStubrithday(rs.getString("stubrithday")); //学生生日
 23 			d.setStuschool(rs.getString("stuschool")); //学生就读于那个学校
 24 			d.setStugrade(rs.getString("stugrade")); //学生是几年级的
 25 			d.setStudepartment(rs.getInt("studepartment"));//中/英文部	dic: 1   中文部   2英文部 
 26 			d.setStuRegistration(rs.getString("stuRegistration")); //报名方式  dic: 0 :晚托班 1:1对1辅导 2:上门家教服务 3:其他
 27 			d.setStupickUp(rs.getInt("stupickUp")); //是否接送  dic: 1 接送 ;0 :不接送
 28 			d.setStuattention(rs.getString("stuattention")); //注意事项
 29 			d.setStuhobby(rs.getString("stuhobby")); //兴趣爱好
 30 			d.setStuavoidFood(rs.getString("stuavoidFood"));//忌口食物 
 31 			d.setStuallergySmptoms(rs.getString("stuallergySmptoms")); //过敏症状
 32 			d.setStuacuteillness(rs.getString("stuacuteillness")); //急性病史
 33 			d.setStuotherInfo(rs.getString("stuotherInfo")); //其他信息
 34 			d.setPrId(rs.getLong("prId"));//家长信息表主键
 35 			d.setStustatus(rs.getInt("stustatus"));//学生有效状态  dic: 0 无效 1:有效
 36 			d.setStuapplyTime(rs.getDate("stuapplyTime")); //注册时间
 37 			d.setUserid(rs.getInt("userId")); //注册人id
 38 			d.setDruguse(rs.getString("druguse")); //drug use  药物使用
 39 			d.setStuschoolTech(rs.getString("stuschool_tech"));//学生老师
 40 			d.setStuschoolTechTel(rs.getString("stuschool_tech_tel"));//学生老师电话
 41 			d.setStartStudayDate(rs.getString("start_studay_date"));//课程开始时间
 42 		 	d.setEndStudayDate(rs.getString("end_studay_date"));//课程结束时间
 43  			d.setStudayCost(rs.getString("studay_cost"));
 44 		}catch(Exception ex){
 45 			ex.printStackTrace();
 46 		}
 47 	return d;
 48 	}
 49 
 50 }
 51 

=参考二:============================================================

Config类

读取同一包下的数据库连接配置文件,这样是为了更好的通用性考虑

  1 package com.tly.dbutil;
  2 
  3 import java.io.IOException;
  4 import java.util.Properties;
  5 
  6 public class Config {
  7     private static Properties prop = new Properties();
  8     static{
  9         try {
 10             //加载dbconfig.properties配置文件
 11             prop.load(Config.class.getResourceAsStream("dbconfig.properties"));
 12         } catch (IOException e) {
 13             // TODO Auto-generated catch block
 14             e.printStackTrace();
 15         }
 16     }
 17 
 18     //设置常量
 19     public static final String CLASS_NAME = prop.getProperty("CLASS_NAME");
 20     public static final String DATABASE_URL = prop.getProperty("DATABASE_URL");
 21     public static final String SERVER_IP = prop.getProperty("SERVER_IP");
 22     public static final String SERVER_PORT = prop.getProperty("SERVER_PORT");
 23     public static final String DATABASE_SID = prop.getProperty("DATABASE_SID");
 24     public static final String USERNAME = prop.getProperty("USERNAME");
 25     public static final String PASSWORD = prop.getProperty("PASSWORD");
 26 
 27 }

dbconfig.properties:数据库配置文件,你也可以用xml格式等,注意Config类里面该文件的调用位置

  1 CLASS_NAME=com.mysql.jdbc.Driver
  2 DATABASE_URL=jdbc:mysql
  3 SERVER_IP=localhost
  4 SERVER_PORT=3306
  5 DATABASE_SID=employees
  6 USERNAME=root
  7 PASSWORD=1

接下来就是数据库连接辅助类DBConn了

  1 package com.employees.dbutil;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DriverManager;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 import java.sql.SQLException;
  8 
  9 
 10 public class DBConn {
 11     //三属性、四方法
 12 
 13     //三大核心接口
 14     private Connection conn = null;
 15     private PreparedStatement pstmt = null;
 16     private ResultSet rs = null;
 17 
 18     //四个方法
 19     //method1: 创建数据库的连接
 20     public Connection getConntion(){
 21         try {
 22             //1: 加载连接驱动,Java反射原理
 23             Class.forName(Config.CLASS_NAME);
 24             //2:创建Connection接口对象,用于获取MySQL数据库的连接对象。三个参数:url连接字符串    账号  密码
 25             String url = Config.DATABASE_URL+"://"+Config.SERVER_IP+":"+Config.SERVER_PORT+"/"+Config.DATABASE_SID;
 26             conn = DriverManager.getConnection(url,Config.USERNAME,Config.PASSWORD);
 27         } catch (ClassNotFoundException e) {
 28             e.printStackTrace();
 29         } catch (SQLException e) {
 30             e.printStackTrace();
 31         }
 32         return conn;
 33     }
 34 
 35 
 36     //method2:关闭数据库的方法
 37     public void closeConn(){
 38         if(rs!=null){
 39             try {
 40                 rs.close();
 41             } catch (SQLException e) {
 42                 e.printStackTrace();
 43             }
 44         }
 45         if(pstmt!=null){
 46             try {
 47                 pstmt.close();
 48             } catch (SQLException e) {
 49                 e.printStackTrace();
 50             }
 51         }
 52         if(conn!=null){
 53             try {
 54                 conn.close();
 55             } catch (SQLException e) {
 56                 e.printStackTrace();
 57             }
 58         }
 59     }
 60 
 61 
 62     //method3: 专门用于发送增删改语句的方法
 63     public int execOther(PreparedStatement pstmt){
 64         try {
 65             //1、使用Statement对象发送SQL语句
 66             int affectedRows = pstmt.executeUpdate();
 67             //2、返回结果
 68             return affectedRows;
 69         } catch (SQLException e) {
 70             e.printStackTrace();
 71             return -1;
 72         }
 73     }
 74 
 75 
 76     //method4: 专门用于发送查询语句
 77     public ResultSet execQuery(PreparedStatement pstmt){
 78         try {
 79             //1、使用Statement对象发送SQL语句
 80             rs = pstmt.executeQuery();
 81             //2、返回结果
 82             return rs;
 83         } catch (SQLException e) {
 84             e.printStackTrace();
 85             return null;
 86         }
 87     }
 88 
 89 }

平时的用上面的代码能够解决一些简单的CRUD的应用了,但是还有很多限制,比如每次程序拿连接都要new,这样就给系统加大了负担,没有事务,没有dataSource等等,今天看见一哥们在园里面写的一篇用反射解决直接以对象参数的方式CRUD,这个我以前也写过,没写完,主要是自己想写一个通用的DButil,最后研究来研究去,发现越来越和hibernate里面的simpleJdbcTemplate接近了,所以就直接去看hibernate的源码了,加上那段时间有些事,没有时间,就将这件事闲置起来了,现在把这个东西补上,也给自己回顾一下下

BaseDao类

  1 package com.employees.dao;
  2 import java.io.InputStream;
  3 import java.lang.reflect.Method;
  4 import java.lang.reflect.ParameterizedType;
  5 import java.sql.Connection;
  6 import java.sql.Date;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.util.ArrayList;
 10 import java.util.Iterator;
 11 import java.util.List;
 12 
 13 import com.employees.dbutil.DBConn;
 14 
 15 public class BaseDAO<T> {
 16 
 17     DBConn conn = new DBConn();
 18     private Connection connection = null;
 19 
 20     @SuppressWarnings("unused")
 21     private Class<T> persistentClass;
 22 
 23     @SuppressWarnings("unchecked")
 24     public BaseDAO() {
 25         initConnection();
 26         //获得参数化类型        
 27         ParameterizedType type = (ParameterizedType)getClass().getGenericSuperclass();
 28         persistentClass = (Class<T>)type.getActualTypeArguments()[0];
 29     }
 30 
 31 
 32     /**
 33      * 获得数据库连接
 34      */
 35     public void initConnection() {
 36         connection = conn.getConntion();
 37     }
 38 
 39 
 40     /**
 41      * 保存
 42      */
 43     public void save(T entity) throws Exception{
 44         //SQL语句,insert into table name (
 45         String sql = "insert into " + entity.getClass().getSimpleName().toLowerCase() + "(";
 46 
 47         //获得带有字符串get的所有方法的对象
 48         List<Method> list = this.matchPojoMethods(entity,"get");
 49 
 50         Iterator<Method> iter = list.iterator();
 51 
 52         //拼接字段顺序 insert into table name(id,name,email,
 53         while(iter.hasNext()) {
 54             Method method = iter.next();
 55             sql += method.getName().substring(3).toLowerCase() + ",";
 56         }
 57 
 58         //去掉最后一个,符号insert insert into table name(id,name,email) values(
 59         sql = sql.substring(0, sql.lastIndexOf(",")) + ") values(";
 60 
 61         //拼装预编译SQL语句insert insert into table name(id,name,email) values(?,?,?,
 62         for(int j = 0; j < list.size(); j++) {
 63             sql += "?,";
 64         }
 65 
 66         //去掉SQL语句最后一个,符号insert insert into table name(id,name,email) values(?,?,?);
 67         sql = sql.substring(0, sql.lastIndexOf(",")) + ")";
 68 
 69         //到此SQL语句拼接完成,打印SQL语句
 70         System.out.println(sql);
 71 
 72         //获得预编译对象的引用
 73         PreparedStatement statement = connection.prepareStatement(sql);
 74 
 75         int i = 0;
 76         //把指向迭代器最后一行的指针移到第一行.
 77         iter = list.iterator();
 78         while(iter.hasNext()) {
 79             Method method = iter.next();
 80             //此初判断返回值的类型,因为存入数据库时有的字段值格式需要改变,比如String,SQL语句是'"+abc+"'
 81             if(method.getReturnType().getSimpleName().indexOf("String") != -1) {
 82                 statement.setString(++i, this.getString(method, entity));
 83             } else if(method.getReturnType().getSimpleName().indexOf("Date") != -1){
 84                 statement.setDate(++i, this.getDate(method, entity));
 85             } else if(method.getReturnType().getSimpleName().indexOf("InputStream") != -1) {
 86                 statement.setAsciiStream(++i, this.getBlob(method, entity),1440);
 87             } else {
 88                 statement.setInt(++i, this.getInt(method, entity));
 89             }
 90         }
 91         //执行
 92         conn.execOther(statement);
 93         //关闭连接
 94         conn.closeConn();
 95     }
 96 
 97 
 98     /**
 99      * 修改
100      */
101     public void update(T entity) throws Exception{
102         String sql = "update " + entity.getClass().getSimpleName().toLowerCase() + " set ";
103 
104         //获得该类所有get方法对象集合
105         List<Method> list = this.matchPojoMethods(entity,"get");
106 
107         //临时Method对象,负责迭代时装method对象.
108         Method tempMethod = null;
109 
110         //由于修改时不需要修改ID,所以按顺序加参数则应该把Id移到最后.
111         Method idMethod = null;
112         Iterator<Method> iter = list.iterator();
113         while(iter.hasNext()) {
114             tempMethod = iter.next();
115             //如果方法名中带有ID字符串并且长度为2,则视为ID.
116             if(tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
117                 //把ID字段的对象存放到一个变量中,然后在集合中删掉.
118                 idMethod = tempMethod;
119                 iter.remove();
120             //如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为ID
121             } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
122                 idMethod = tempMethod;
123                 iter.remove();
124             }
125         }
126 
127         //把迭代指针移到第一位
128         iter = list.iterator();
129         while(iter.hasNext()) {
130             tempMethod = iter.next();
131             sql += tempMethod.getName().substring(3).toLowerCase() + "= ?,";
132         }
133 
134         //去掉最后一个,符号
135         sql = sql.substring(0,sql.lastIndexOf(","));
136 
137         //添加条件
138         sql += " where " + idMethod.getName().substring(3).toLowerCase() + " = ?";
139 
140         //SQL拼接完成,打印SQL语句
141         System.out.println(sql);
142 
143         PreparedStatement statement = this.connection.prepareStatement(sql);
144 
145         int i = 0;
146         iter = list.iterator();
147         while(iter.hasNext()) {
148             Method method = iter.next();
149             //此初判断返回值的类型,因为存入数据库时有的字段值格式需要改变,比如String,SQL语句是'"+abc+"'
150             if(method.getReturnType().getSimpleName().indexOf("String") != -1) {
151                 statement.setString(++i, this.getString(method, entity));
152             } else if(method.getReturnType().getSimpleName().indexOf("Date") != -1){
153                 statement.setDate(++i, this.getDate(method, entity));
154             } else if(method.getReturnType().getSimpleName().indexOf("InputStream") != -1) {
155                 statement.setAsciiStream(++i, this.getBlob(method, entity),1440);
156             } else {
157                 statement.setInt(++i, this.getInt(method, entity));
158             }
159         }
160 
161         //为Id字段添加值
162         if(idMethod.getReturnType().getSimpleName().indexOf("String") != -1) {
163             statement.setString(++i, this.getString(idMethod, entity));
164         } else {
165             statement.setInt(++i, this.getInt(idMethod, entity));
166         }
167 
168         //执行SQL语句
169         statement.executeUpdate();
170 
171                 //关闭预编译对象
172                 statement.close();
173 
174                 //关闭连接
175                 connection.close();
176     }
177 
178 
179     /**
180      * 删除
181      */
182     public void delete(T entity) throws Exception{
183         String sql = "delete from " + entity.getClass().getSimpleName().toLowerCase() + " where ";
184 
185         //存放字符串为"id"的字段对象
186         Method idMethod = null;
187 
188         //取得字符串为"id"的字段对象
189         List<Method> list = this.matchPojoMethods(entity, "get");
190         Iterator<Method> iter = list.iterator();
191         while(iter.hasNext()) {
192             Method tempMethod = iter.next();
193             //如果方法名中带有ID字符串并且长度为2,则视为ID.
194             if(tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
195                 //把ID字段的对象存放到一个变量中,然后在集合中删掉.
196                 idMethod = tempMethod;
197                 iter.remove();
198             //如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为ID
199             } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
200                 idMethod = tempMethod;
201                 iter.remove();
202             }
203         }
204 
205         sql += idMethod.getName().substring(3).toLowerCase() + " = ?";
206 
207         PreparedStatement statement = this.connection.prepareStatement(sql);
208 
209         //为Id字段添加值
210         int i = 0;
211         if(idMethod.getReturnType().getSimpleName().indexOf("String") != -1) {
212             statement.setString(++i, this.getString(idMethod, entity));
213         } else {
214             statement.setInt(++i, this.getInt(idMethod, entity));
215         }
216 
217         //执行
218         conn.execOther(statement);
219         //关闭连接
220         conn.closeConn();
221     }
222 
223 
224     /**
225      * 通过ID查询
226      */
227     public T findById(Object object) throws Exception{
228         String sql = "select * from " + persistentClass.getSimpleName().toLowerCase() + " where ";
229 
230         //通过子类的构造函数,获得参数化类型的具体类型.比如BaseDAO<T>也就是获得T的具体类型
231         T entity = persistentClass.newInstance();
232 
233         //存放Pojo(或被操作表)主键的方法对象
234         Method idMethod = null;
235 
236         List<Method> list = this.matchPojoMethods(entity, "set");
237         Iterator<Method> iter = list.iterator();
238 
239         //过滤取得Method对象
240         while(iter.hasNext()) {
241             Method tempMethod = iter.next();
242             if(tempMethod.getName().indexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
243                 idMethod = tempMethod;
244             } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))){
245                 idMethod = tempMethod;
246             }
247         }
248         //第一个字母转为小写
249         sql += idMethod.getName().substring(3,4).toLowerCase()+idMethod.getName().substring(4) + " = ?";
250 
251         //封装语句完毕,打印sql语句
252         System.out.println(sql);
253 
254         //获得连接
255         PreparedStatement statement = this.connection.prepareStatement(sql);
256 
257         //判断id的类型
258         if(object instanceof Integer) {
259             statement.setInt(1, (Integer)object);
260         } else if(object instanceof String){
261             statement.setString(1, (String)object);
262         }
263 
264         //执行sql,取得查询结果集.
265         ResultSet rs = conn.execQuery(statement);
266 
267         //记数器,记录循环到第几个字段
268         int i = 0;
269 
270         //把指针指向迭代器第一行
271         iter = list.iterator();
272 
273         //封装
274         while(rs.next()) {
275             while(iter.hasNext()) {
276                 Method method = iter.next();
277                 if(method.getParameterTypes()[0].getSimpleName().indexOf("String") != -1) {
278                     //由于list集合中,method对象取出的方法顺序与数据库字段顺序不一致(比如:list的第一个方法是setDate,而数据库按顺序取的是"123"值)
279                     //所以数据库字段采用名字对应的方式取.
280                     this.setString(method, entity, rs.getString(method.getName().substring(3).toLowerCase()));
281                 } else if(method.getParameterTypes()[0].getSimpleName().indexOf("Date") != -1){
282                     this.setDate(method, entity, rs.getDate(method.getName().substring(3).toLowerCase()));
283                 } else if(method.getParameterTypes()[0].getSimpleName().indexOf("InputStream") != -1) {
284                     this.setBlob(method, entity, rs.getBlob(method.getName().substring(3).toLowerCase()).getBinaryStream());
285                 } else {
286                     this.setInt(method, entity, rs.getInt(method.getName().substring(3).toLowerCase()));
287                 }
288             }
289         }
290 
291         //关闭结果集
292         rs.close();
293 
294         //关闭预编译对象
295         statement.close();
296 
297         return entity;
298     }
299 
300 
301     /**
302      * 过滤当前Pojo类所有带传入字符串的Method对象,返回List集合.
303      */
304     private List<Method> matchPojoMethods(T entity,String methodName) {
305         //获得当前Pojo所有方法对象
306         Method[] methods = entity.getClass().getDeclaredMethods();
307 
308         //List容器存放所有带get字符串的Method对象
309         List<Method> list = new ArrayList<Method>();
310 
311         //过滤当前Pojo类所有带get字符串的Method对象,存入List容器
312         for(int index = 0; index < methods.length; index++) {
313             if(methods[index].getName().indexOf(methodName) != -1) {
314                 list.add(methods[index]);
315             }
316         }
317         return list;
318     }
319 
320 
321     /**
322      * 方法返回类型为int或Integer类型时,返回的SQL语句值.对应get
323      */
324     public Integer getInt(Method method, T entity) throws Exception{
325         return (Integer)method.invoke(entity, new Object[]{});
326     }
327 
328     /**
329      * 方法返回类型为String时,返回的SQL语句拼装值.比如'abc',对应get
330      */
331     public String getString(Method method, T entity) throws Exception{
332         return (String)method.invoke(entity, new Object[]{});
333     }
334 
335     /**
336      * 方法返回类型为Blob时,返回的SQL语句拼装值.对应get
337      */
338     public InputStream getBlob(Method method, T entity) throws Exception{
339         return (InputStream)method.invoke(entity, new Object[]{});
340     }
341 
342 
343     /**
344      * 方法返回类型为Date时,返回的SQL语句拼装值,对应get
345      */
346     public Date getDate(Method method, T entity) throws Exception{
347         return (Date)method.invoke(entity, new Object[]{});
348     }
349 
350 
351     /**
352      * 参数类型为Integer或int时,为entity字段设置参数,对应set
353      */
354     public Integer setInt(Method method, T entity, Integer arg) throws Exception{
355         return (Integer)method.invoke(entity, new Object[]{arg});
356     }
357 
358     /**
359      * 参数类型为String时,为entity字段设置参数,对应set
360      */
361     public String setString(Method method, T entity, String arg) throws Exception{
362         return (String)method.invoke(entity, new Object[]{arg});
363     }
364 
365     /**
366      * 参数类型为InputStream时,为entity字段设置参数,对应set
367      */
368     public InputStream setBlob(Method method, T entity, InputStream arg) throws Exception{
369         return (InputStream)method.invoke(entity, new Object[]{arg});
370     }
371 
372 
373     /**
374      * 参数类型为Date时,为entity字段设置参数,对应set
375      */
376     public Date setDate(Method method, T entity, Date arg) throws Exception{
377         return (Date)method.invoke(entity, new Object[]{arg});
378     }
379 }

EmployeesDao继承BaseDAO,可以直接使用父类的方法,增加了代码的复用

  1 package com.employees.dao;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 import com.employees.po.Employees;
  6 
  7 public class EmployeesDao extends BaseDAO<Employees> {
  8 
  9     // 添加员工信息的操作
 10     public boolean addEmployees(final Employees employees) throws Exception {
 11         save(employees);
 12         return true;
 13     }
 14 
 15     // 将员工信息添加到表格中
 16     public List<Employees> addEmployees(int id) throws Exception {
 17         List<Employees> lstEmployees = new ArrayList<Employees>();
 18         Employees employees = findById(id);
 19         // 将当前封转好的数据装入对象中
 20         lstEmployees.add(employees);
 21         return lstEmployees;
 22     }
 23 
 24     public void deleteEmp(final Employees entity) throws Exception {
 25         this.delete(entity);
 26     }
 27 
 28     public void updateEmp(final Employees entity) throws Exception {
 29         this.update(entity);
 30     }
 31 
 32 
 33 }

po层的代码就不贴了,现在用junit4做一下测试

  1 package com.employees.dao;
  2 
  3 import org.junit.Test;
  4 
  5 import com.employees.po.Employees;
  6 
  7 public class EmployeesDaoTest {
  8 
  9     @Test
 10     public void testAdd() throws Exception {
 11         Employees emp = new Employees();
 12         emp.setPname("tly");
 13         emp.setPsex("");
 14         emp.setPbeliefs("xxxxx");
 15         emp.setPaddr("天河");
 16         emp.setPhobby("打篮球");
 17         emp.setPsubject("计算机");
 18         emp.setPtel("123456");
 19         EmployeesDao dao = new EmployeesDao();
 20         dao.addEmployees(emp);
 21     }
 22     @Test
 23     public void testUpdate() throws Exception {
 24         EmployeesDao dao = new EmployeesDao();
 25         Employees emp = dao.findById(14);
 26         emp.setPtel("999999");
 27         dao.updateEmp(emp);
 28     }
 29     @Test
 30     public void testdelete() throws Exception {
 31         EmployeesDao dao = new EmployeesDao();
 32         Employees emp = dao.findById(15);
 33         dao.deleteEmp(emp);
 34     }
 35 
 36 }

注:该段内容来自:cnblogs:牛奶、不加糖

原文地址:https://www.cnblogs.com/ios9/p/Java_Jdbc_info.html