JDBC辅助类封装 及应用

时间:2023-03-10 01:44:55
JDBC辅助类封装 及应用

一:代码图解:

JDBC辅助类封装 及应用

二:配置文件:

 driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://127.0.0.1\:3306/xlzj_sh_new?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNull
username=root
password=123456
filters=stat
initialSize=10
maxActive=200
maxWait=60000
#maxIdle=15
minIdle=10
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 'x'
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=20
#\u7981\u7528\u5BF9\u4E8E\u957F\u65F6\u95F4\u4E0D\u4F7F\u7528\u7684\u8FDE\u63A5\u5F3A\u5236\u5173\u95ED\u7684\u529F\u80FD
removeAbandoned=false
#\u8D85\u8FC730\u5206\u949F\u5F00\u59CB\u5173\u95ED\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u7531\u4E8EremoveAbandoned\u4E3Afalse\uFF0C\u8FD9\u4E2A\u8BBE\u7F6E\u9879\u4E0D\u518D\u8D77\u4F5C\u7528
removeAbandonedTimeout=1800
#\u5C06\u5F53\u524D\u5173\u95ED\u52A8\u4F5C\u8BB0\u5F55\u5230\u65E5\u5FD7\uFF0C\u7531\u4E8EremoveAbandoned\u4E3Afalse\uFF0C\u8FD9\u4E2A\u8BBE\u7F6E\u9879\u4E0D\u518D\u8D77\u4F5C\u7528
logAbandoned=true

三:获取配置文件信息

JDBC辅助类封装 及应用

PathUtil.java

 package com.jacezhu.framework.utils.BeanUtil.pathUtil;

 import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties; /**
*
*     * 项目名称:text    * 类名称:PathUtil    * 类描述:   获取文件路径
* 创建人: 刘军/shall_liu  * 创建时间:2015年11月17日 下午4:10:31    * 修改人:Administrator    * 修改时间:2015年11月17日 下午4:10:31    * 修改备注:    * @version     *     */
public class PathUtil {
/**
* 获取 获取人参文件的 路径
* @return
*/
public static String getPath(String fileName){
String path=getPath(getFileUrl(), fileName);
return path;
}
/**
* 获取:入参 properties配置文件里面的值(key_value)
* @param FileName(*.properties <配置文件名称.properties>)
* @return properties 对象
*/
public static Properties returnPropertiesValue(String FileName){
return readData(getPath(FileName));
} /**
*
* @Title: getPath  * @Description: (根据URl 获取指定文件的路径)
* @param @param url
* @param @return    设定文件  * @return String    返回类型  * @throws  * 创建者:刘军/shall_liu
* 创建时间:2015年11月18日下午2:06:50
*/
public static String getPath(URL url,String fileName){
String path = (url + fileName );
int index=lookindex(path,'/');
String newPath=path.substring(index+1, path.length());
return newPath;
}
/**
*
* @Title: getFileUrl  * @Description: (获取根目录路径)
* @param @return    设定文件  * @return URL    返回类型  * @throws  * 创建者:刘军/shall_liu
* 创建时间:2015年11月18日下午2:04:23
*/
public static URL getFileUrl(){
URL url = ClassLoader.getSystemClassLoader().getResource("./");
return url;
} /**
* 获取 某个字符在某个字符串第一次出现的位置
* @param string
* @param s
* @return
*/
public static int lookindex(String string, char s) { int number = 0;
int index=-1;//-1 表示没有找到
char arr[] = string.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == s) {
number++;
}
if (number == 1) {
index=i;
return i;
}
}
return index;
}
/**
*
* @Title: lookindex  * @Description: (判断字符 c在 字符串 string中指定出现的index次数时该字符c在字符串string中的位置)
* @param @param string
* @param @param s
* @param @param indexs
* @param @return    设定文件  * @return int    返回类型  * @throws  * 创建者:刘军/shall_liu
* 创建时间:2015年11月18日下午1:59:27
*/
public static int lookindex(String string, char s,int indexs) {
int number = 0;
int index=-1;//-1 表示没有找到
char arr[] = string.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == s) {
number++;
}
if (number ==indexs) {
index=i;
return i;
}
}
return index;
}
/**
*
* @Title: counter  * @Description: ( 判断字符串c在 字符串source中出现的总次数)
* @param @param source
* @param @param c
* @param @return    设定文件  * @return int    返回类型  * @throws  * 创建者:刘军/shall_liu
* 创建时间:2015年11月18日下午1:57:29
*/
public static int counter(String source,String c){
int counter=0;
if(c ==null||c.trim().equals("")){
counter=0;
}else{
if(!source.trim().equals("")&&source!=null){
String[] newArray=source.split(c);
counter=newArray.length-1;
}
}
return counter;
} public static void main(String[] args) {
String path=getPath("dabase.properties");
System.out.println(path);
} /**
* 获取整个配置文件中的属性
*
* @param filePath
* 文件路径,即文件所在包的路径,例如:java/util/config.properties
*/
public static Properties readData(String filePath) {
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(
filePath));
props.load(in);
in.close();
return props;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} }

PropertiesConfig.java

 package com.jacezhu.framework.utils.BeanUtil.pathUtil;

 import java.io.InputStream;
import java.util.Properties; /**
* 主题:读取Config文件工具类 P
*
* @author 刘军/shell_liu 2015-4-14
*/
public class PropertiesConfig { /**
*
* @Title: getProperties  * @Description:
* (TestProperties.class.getClassLoader().getResourceAsStream
* ("db.properties" );
* 类名.class.类加载器.从文件流中获取资源("放在程序根目录下的properties文件中的内容")
* loader: 载入程序;装货设备;装填器)  * @param @param fileName
* @param @return    设定文件  * @return Properties    返回类型  * @throws  */
public static Properties getProperties(String fileName) {
/*
* 从properties文件中读取文件思路: 1:声明对象:Properties props=new Properties();
* 2:调用获取properties文件内容的流方法:props.load(inStream); 3:将src
* /db.propreties以InputStream方式载入 inStream=
* TestProperties.class.getClassLoader
* ().getResourceAsStream("db.properties"); 4://读取props中文件信息 String
* name=props.getProperty("uesrname");
*/
Properties props = new Properties();
try {
// 将src /db.propreties以InputStream方式载入
InputStream inStream = PropertiesConfig.class
.getResourceAsStream(fileName);
props.load(inStream); } catch (Exception e) {
e.printStackTrace();
}
return props;
} public static void main(String[] args) {
Properties properties = new Properties();
properties = getProperties("/dabase.properties");
System.out.println(properties);
}
}

PropertyReadUtil.java

 package com.jacezhu.framework.utils.BeanUtil.pathUtil;

 import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties; /**
* 主题: *.properties 配置文件内容读取工具
* @author 刘军/shell_liu
* 2015-9-8
*/ public class PropertyReadUtil {
//获取项目根文件路径地址
static String path = Thread.currentThread().getContextClassLoader() .getResource("").getPath();
/**
*
* @param propertiesName 需要被读取的配置文件
* @return Properties对象
* @描述 :*.properties 配置文件内容读取 方法
* @author 刘军/shell_liu
* @创建日期 2015-9-8
* @创建时间 下午5:31:05
*
*/
public static Properties getProperties(String propertiesName){
Properties prop = new Properties();
InputStream in;
try {
in = new BufferedInputStream (new FileInputStream(path+propertiesName));
prop.load(in); ///加载属性列表
} catch(Exception e){
System.out.println(e);
} return prop; } public static void main(String[] args) {
Properties prop = new Properties();
prop=getProperties("database.properties");
Iterator<String> it=prop.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
System.out.println(key+":"+prop.getProperty(key));
} }
}

四:JDBC 获取连接的封装

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

 package com.jacezhu.framework.connectUtil;

 import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; /**
* The Class DruidDataSource.
*/
public class DruidDataSourceUtil { /** 使用配置文件构建Druid数据源. */
public static final int DRUID_MYSQL_SOURCE = 0; /** 使用配置文件构建Druid数据源. */
public static final int DRUID_MYSQL_SOURCE2 = 1; /** 使用配置文件构建Dbcp数据源. */
public static final int DBCP_SOURCE = 4;
public static String confile = "jdbc.properties";
public static Properties p = null; static {
p = new Properties();
InputStream inputStream = null;
try {
//java应用
confile = DruidDataSourceUtil.class.getClassLoader().getResource("").getPath()+ confile;
System.out.println(confile);
File file = new File(confile);
inputStream = new BufferedInputStream(new FileInputStream(file));
p.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 根据类型获取数据源
*
* @param sourceType
* 数据源类型
* @return druid或者dbcp数据源
* @throws Exception
* the exception
*/
public static final DataSource getDataSource(int sourceType) throws Exception {
DataSource dataSource = null;
switch (sourceType) {
case DRUID_MYSQL_SOURCE:
dataSource = DruidDataSourceFactory.createDataSource(p);
break;
case DRUID_MYSQL_SOURCE2:
dataSource = DruidDataSourceFactory.createDataSource(p);
break;
case DBCP_SOURCE:
// dataSource = BasicDataSourceFactory.createDataSource(
// MySqlConfigProperty.getInstance().getProperties());
break;
}
return dataSource;
}
public static void main(String[] args) throws Exception {
int dbType=0;
DataSource dataSource=DruidDataSourceUtil.getDataSource(dbType); }
}

c3p0连接池管理类  DataSourceConnUtil.java

 package com.jacezhu.framework.connectUtil;

 import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties; import javax.sql.DataSource; import com.mchange.v2.c3p0.DataSources; /**
*
*     * 项目名称:s4h4s2s    * 类名称:DataSourceConnUtil    * 类描述: c3p0连接池管理类   * 创建人:刘军/jun liu    * 创建时间:2015-12-19 下午11:40:35    * 修改人:刘军/shall_liu    * 修改时间:2015-12-19 下午11:40:35    * 修改备注:    * @version     *     */
public class DataSourceConnUtil { private static final String JDBC_DRIVER = "driverClass";
private static final String JDBC_URL = "jdbcUrl"; private static DataSource ds;
/**
* 初始化连接池代码块
*/
static{
initDBSource();
} /**
* 初始化c3p0连接池
*/
private static final void initDBSource(){
Properties c3p0Pro = new Properties();
try {
//加载配置文件
c3p0Pro.load(DataSourceConnUtil.class.getResourceAsStream("/config.properties"));
//c3p0Pro.load(new FileInputStream(PathUtil.getPath("dabase.properties")));
} catch (Exception e) {
e.printStackTrace();
} String drverClass = c3p0Pro.getProperty(JDBC_DRIVER);
if(drverClass != null){
try {
//加载驱动类
Class.forName(drverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} } Properties jdbcpropes = new Properties();
Properties c3propes = new Properties();
for(Object key:c3p0Pro.keySet()){
String skey = (String)key;
if(skey.startsWith("c3p0.")){
c3propes.put(skey, c3p0Pro.getProperty(skey));
}else{
jdbcpropes.put(skey, c3p0Pro.getProperty(skey));
}
} try {
//建立连接池
DataSource unPooled = DataSources.unpooledDataSource(c3p0Pro.getProperty(JDBC_URL),jdbcpropes);
ds = DataSources.pooledDataSource(unPooled,c3propes); } catch (SQLException e) {
e.printStackTrace();
}
} /**
* 获取数据库连接对象
* @return 数据连接对象
* @throws SQLException
*/
public static synchronized Connection getConnection() {
Connection conn = null;
try {
conn = ds.getConnection();
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
conn.setAutoCommit(false);//取消 事务管理:事务提交机制
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}

普通的 数据库连接  ConnUtil.java

 package com.jacezhu.framework.connectUtil;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties; import javax.servlet.ServletException; /**
*
*     * 项目名称:s4h4s2s    * 类名称:ConnUtil    * 类描述:  主题:数据库连接工具类——包含取得连接和关闭资源; 没有数据库连接池    * 创建人:刘军/jun liu    * 创建时间:2015-12-19 下午11:40:21    * 修改人:刘军/shall_liu    * 修改时间:2015-12-19 下午11:40:21    * 修改备注:    * @version     *     */
public class ConnUtil {
private static Connection conn = null;
private static String DRIVER_NAME;
private static String URL;
private static String USER_NAME;
private static String PASSWORD; static {
try {
getConn();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 得到连接(没有入参)
*
* @return
*/
public static Connection getConn() {
try {
if (conn == null || conn.isValid(10) == false) {
ConnUtil connInfo = getConnectInfo();
conn = getConn(connInfo);
}
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{ try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} /**
* 获取:ConnUtil 数据库连接参数的值
*
* @return MerchatInfo 对象
* @描述 :从 dabase.properties配置文件获取 value 的值赋值给Properties 对象
* @author 刘军/shell_liu
* @创建日期 2015-9-8
* @创建时间 下午9:04:32
*
*/
public static ConnUtil getConnectInfo() {
ConnUtil connInfo = new ConnUtil();
try {
Properties properties=new Properties();
//获取 配置文件的key-value
properties.load(ConnUtil.class.getResourceAsStream("/config.properties"));
//properties = PathUtil.returnPropertiesValue("dabase.properties"); ConnUtil.setDRIVER_NAME(properties.getProperty("driverClass"));
ConnUtil.setURL(properties.getProperty("jdbcUrl"));
ConnUtil.setUSER_NAME(properties.getProperty("user"));
ConnUtil.setPASSWORD(properties.getProperty("password"));
return connInfo;
} catch (Exception e) {
try {
throw new ServletException("加载数据库链接参数失败"); } catch (ServletException e1) {
e1.printStackTrace();
return null;
}
}
} /**
* 得到连接
*
* @param connUtil
* (数据库连接需要的值)
* @return
*/
@SuppressWarnings("static-access")
public static Connection getConn(ConnUtil connUtil) {
try {
Class.forName(connUtil.getDRIVER_NAME());
conn = DriverManager.getConnection(connUtil.getURL(),
connUtil.getUSER_NAME(), connUtil.getPASSWORD());
conn.setAutoCommit(false);//取消 事务管理:事务提交机制
} catch (Exception e) {
try {
throw new ServletException("链接数据库失败!");
} catch (ServletException e1) {
e1.printStackTrace();
}
}
return conn;
} /**
* 关闭连接
*
* @param conn
* @throws SQLException
*/
public static void close(Connection conn) throws SQLException {
if (conn != null) {
conn.close();
conn = null;
}
} /**
* 关闭PreparedStatement
*
* @param pstmt
* @throws SQLException
*/
public static void close(PreparedStatement pstmt) throws SQLException {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} /**
* 关闭结果集
*
* @param rs
* @throws SQLException
*/
public static void close(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
rs = null;
}
} //----------------------get set-------------------------------------------------
/**
*
* @Title: getDRIVER_NAME  * @Description: ()  * @param @return    设定文件  * @return String    返回类型  * @throws  */
public static String getDRIVER_NAME() {
return DRIVER_NAME;
} public static void setDRIVER_NAME(String dRIVER_NAME) {
DRIVER_NAME = dRIVER_NAME;
} public static String getURL() {
return URL;
} public static void setURL(String uRL) {
URL = uRL;
} public static String getUSER_NAME() {
return USER_NAME;
} public static void setUSER_NAME(String uSER_NAME) {
USER_NAME = uSER_NAME;
} public static String getPASSWORD() {
return PASSWORD;
} public static void setPASSWORD(String pASSWORD) {
PASSWORD = pASSWORD;
}
//--------------------main 方法----------------------------------------------
/**
* 测试 连接是否成功
*
* @param args
*/
public static void main(String[] args) {
getConn();
}
}

SqlParameter.java

 package com.jacezhu.framework.connectUtil.jdbcUtl;
/**
*
* @Title: SqlParameter.java  * @Package com.jacezhu.framework.connectUtil.jdbcUtl  * @Description: (存储过程参数类型)  * @author 刘军
* @date 2016-3-19 下午2:47:02  * @version V1.0   */
public class SqlParameter { /**
* 参数名称
*/
public String Name;
/**
* 参数值
*/
public Object Value;
/**
* true表示参数为输出类型
*/
public boolean OutPut;
/**
* 参数类型
*/
public int Type;
/**
* 输入类型参数的构造函数
* @param name 存储过程 输入类型 参数名称
* @param value 存储过程 输入类型 参数值
*/
public SqlParameter(String name,Object value){
this.Name = name;
this.Value= value;
}
/**
* 输出类型参数的构造函数
* @param type 存储过程 输出类型 参数类型
* @param name 存储过程 输出类型 参数名称
*/
public SqlParameter(int type,String name){
this.Name = name;
this.OutPut = true;
this.Type = type;
}
/**
* 返回类型参数的构造函数
* @param type 存储过程 返回类型
*/
public SqlParameter(int type){
this.Name = "";
this.OutPut = true;
this.Type = type;
}
}

PageModel.java

 package com.jacezhu.framework.connectUtil.jdbcUtl;
import java.util.List;
/**
* 分页封装类
*     * 项目名称:s4h4s2s    * 类名称:PageModel    * 类描述:    * 创建人:刘军/jun liu    * 创建时间:2015-12-20 下午2:40:55    * 修改人:Administrator    * 修改时间:2015-12-20 下午2:40:55    * 修改备注:    * @version     *     */
public class PageModel<T> { //结果集
private List<T> list; //记录数
private int totalRecords; //每页多少条数据
private int pageSize; //第几页
private int pageNo;
//总共多少页
private int countPageNo; /**
* 返回总页数
* @return
*/
public int getTotalPages() {
return (totalRecords + pageSize - 1) / pageSize;
} /**
* 首页
* @return
*/
public int getTopPageNo() {
return 1;
} /**
* 上一页
* @return
*/
public int getPreviousPageNo() {
if (this.pageNo <= 1) {
return 1;
}
return this.pageNo - 1;
} /**
* 下一页
* @return
*/
public int getNextPageNo() {
if (this.pageNo >= getButtomPageNo()) {
return getButtomPageNo();
}
return this.pageNo + 1;
} /**
* 尾页
* @return
*/
public int getButtomPageNo() {
return getTotalPages();
} public List<T> getList() {
return list;
} public void setList(List<T> list) {
this.list = list;
} public int getTotalRecords() {
return totalRecords;
} public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
} public int getPageSize() {
return pageSize;
} public void setPageSize(int pageSize) {
this.pageSize = pageSize;
} public int getPageNo() {
return pageNo;
} public void setPageNo(int pageNo) {
this.pageNo = pageNo;
} public int getCountPageNo() {
return countPageNo;
} public void setCountPageNo(int countPageNo) {
this.countPageNo = countPageNo;
} }

ObjectMapper.java

 package com.jacezhu.framework.connectUtil.jdbcUtl;

 import java.sql.ResultSet;
/**
*
* @Title: ObjectMapper.java  * @Package com.jacezhu.framework.connectUtil.jdbcUtl  * @Description: (用于转换数据结果集 )  * @author 刘军
* @date 2016-3-19 上午9:52:18  * @version V1.0   */
public interface ObjectMapper {
public Object mapping(ResultSet rs); }

五:JDBC 封装层:dao层

BaseDaoI.java

 package com.jacezhu.dao;

 import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map; public interface BaseDaoI<T> { public Serializable save(T o); public void delete(T o); public void update(T o); public void saveOrUpdate(T o); public T get(Class<T> c, Serializable id); public T get(String hql); public T get(String hql, Map<String, Object> params); public List<T> find(String hql); public List<T> find(String hql, Map<String, Object> params); public List<T> find(String hql, int page, int rows); public List<T> find(String hql, Map<String, Object> params, int page,
int rows); public Long count(String hql); public Long count(String hql, Map<String, Object> params); public int executeHql(String hql); public int executeHql(String hql, Map<String, Object> params); public List<Object[]> findBySql(String sql); public List<Object[]> findBySql(String sql, int page, int rows); public List<Object[]> findBySql(String sql, Map<String, Object> params); public List<Object[]> findBySql(String sql, Map<String, Object> params,
int page, int rows); public int executeSql(String sql); public int executeSql(String sql, Map<String, Object> params); public BigInteger countBySql(String sql); public BigInteger countBySql(String sql, Map<String, Object> params); public void refresh(T o); public void merge(T o);
}

JdbcBaseDao.java

 package com.jacezhu.dao;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.*;
import java.lang.reflect.*; import com.jacezhu.framework.connectUtil.ConnUtil;
import com.jacezhu.framework.connectUtil.DataSourceConnUtil;
import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
import com.jacezhu.framework.connectUtil.jdbcUtl.SqlParameter; public interface JdbcBaseDao { /**
*
* @author 刘军
* @date 2016-3-19 上午11:14:17  * @version V1.0   * @Title: getStatement  * @Description: ( )  * @param @return
* @param @throws SQLException    设定文件  * @return Connection    返回类型  * @throws  */
public Connection getStatement() throws SQLException; /**
*
* @Title: update  * @Description: (更新:update)  * @param @param sql
* @param @param obj
* @param @param isGenerateKey
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean update(String sql, Object[] obj, boolean isGenerateKey) ;
/**
*
* @Title: updateByPreparedStatement  增加、删除、改
* @Description: (增加、删除、改)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean updateByPreparedStatement(String sql, List<Object> params) ; /**
* insert update delete SQL语句的执行的统一方法
*
* @param sql
* SQL语句
* @param params
* 参数数组,若没有参数则为null
* @return 受影响的行数
*/
public int executeUpdate(String sql, Object[] params) ; /**
*
* @Title: query  * @Description: ( )  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, Object[] obj,
ObjectMapper mapper) ; /**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午1:58:12  * @version V1.0   * @Title: query  * @Description: (
*
*)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, List obj,
ObjectMapper mapper) ; /**
*
* @Title: returnTableCount  * @Description: ( select count(*)from table 的总数据条数)  * @param @param table
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int returnTableCount(String table);
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午11:19:59  * @version V1.0   * @Title: Count  * @Description: (
* 返回 统计count 数据的数量
*)  * @param @param sql
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public long Count(String sql);
/**
*
* @Title: findSimpleResult  获取最后一条(单条)记录
* @Description: (查询单条记录)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return Map<String,Object>    返回类型  * @throws  */
public Map<String, Object> findSimpleResult(String sql, List<Object> params);
/**
* 获取结果集,并将结果放在List中
*
* @param sql
* SQL语句
* @return List 结果集
*/
public List<Object> excuteQuery(String sql, Object[] params) ; /**
*
* @Title: findModeResult  查询多条记录
* @Description: (查询多条记录)  * @param @param sql
* @param @param params
* @param @return
* @param @throws SQLException    设定文件  * @return List<Map<String,Object>>    返回类型  * @throws  */
public List<Map<String, Object>> findModeResult(String sql, List<Object> params) ; /**
* SQL 查询将查询结果:一行一列
*
* @param sql
* SQL语句
* @param params
* 参数数组,若没有参数则为null
* @return 结果集
*/
public Object executeQuerySingle(String sql, Object[] params) ; /**
*
* @Title: findSimpleRefResult  通过反射机制查询单条记录
* @Description: (通过反射机制查询单条记录)  * @param @param sql
* @param @param params
* @param @param cls
* @param @return
* @param @throws Exception    设定文件  * @return T    返回类型  * @throws  */
public <T> T findSimpleRefResult(String sql, List<Object> params,Class<T> cls) ;
/**
* 通过反射机制查询多条记录
*
* @param sql
* @param params
* @param cls
* @return
* @throws Exception
*/
public <T> List<T> findMoreRefResult(String sql, List<Object> params,
Class<T> cls) ; /**
*
* @Title: find  * @Description: ( 查询一条记录)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql, Object[] obj, ObjectMapper mapper) ;
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-14 下午1:18:51  * @version V1.0   * @Title: find  * @Description: (
* 查询一条记录
*)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql, List obj, ObjectMapper mapper);
/**
*
* @Title: executeQuery  统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源
* @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源)  * @param @param sql
* @param @param parameters
* @param @return    设定文件  * @return ArrayList    返回类型  * @throws  */
@SuppressWarnings({ "rawtypes", "unchecked" })
public ArrayList executeQuery(String sql, String[] parameters); /**
*
* @Title: executeQuery  by statement
* @Description: (执行 查询sql 获取结果集)  * @param @param sql
* @param @return statement resultSet
* @param @throws SQLException    设定文件  * @return ResultSet    返回类型  * @throws  */
public ResultSet executeQuery(String sql); //-------------------------------------------对象化--------------- //----------------------存储过程调用------------------------------------------- /**
* 存储过程带有一个输出参数的方法
*
* @param sql
* 存储过程语句
* @param params
* 参数数组
* @param outParamPos
* 输出参数位置
* @param SqlType
* 输出参数类型
* @return 输出参数的值
*/
public Object executeQuery(String sql, Object[] params, int outParamPos,
int SqlType) ; /**
* 执行不返回结果集的存储过程
*
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @throws ClassNotFoundException
* @throws SQLException
*/
public void executeNonQuery(String sql, SqlParameter... params) ; /**
* 执行Insert语句,返回Insert成功之后标识列的值
*
* @param sql
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public int executeIdentity(String sql) ;
/**
* 执行不返回结果集的存储过程
*
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @throws ClassNotFoundException
* @throws SQLException
*/
public void executeNonQuery1(String sql, SqlParameter... params) ;
/**
* 执行返回聚合函数的操作
*
* @param sql
* 含有聚合函数的SQL语句
* @return 聚合函数的执行结果
* @throws SQLException
* @throws ClassNotFoundException
*/
public int executeScalar(String sql) ;
/**
* 执行返回泛型集合的SQL语句
*
* @param cls
* 泛型类型
* @param sql
* 查询SQL语句
* @return 泛型集合
* @throws ClassNotFoundException
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> List<T> executeList(Class<T> cls, String sql) ;
/**
* 执行返回泛型集合的存储过程
*
* @param cls
* 泛型类型
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @return 泛型集合
* @throws ClassNotFoundException
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> List<T> executeList(Class<T> cls, String sql,
SqlParameter... params) ;
/**
* 执行返回泛型类型对象的SQL语句
*
* @param cls
* 泛型类型
* @param sql
* SQL语句
* @return 泛型类型对象
* @throws SQLException
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> T executeEntity(Class<T> cls, String sql) ;
/**
* 执行返回泛型类型对象的存储过程
*
* @param cls
* 泛型类型
* @param sql
* SQL语句
* @param params
* 存储过程参数
* @return 泛型类型对象
* @throws SQLException
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> T executeEntity(Class<T> cls, String sql,
SqlParameter... params) ; /**
*
* @Title: executeUpdate  by statement
* @Description: (更新结果集)  * @param @param sql
* @param @return
* @param @throws SQLException    设定文件  * @return int    返回类型  * @throws  */
@SuppressWarnings("null")
public int executeUpdate(String sql) ; /**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-17 上午11:33:28  * @version V1.0   * @Title: getSeq  * @Description: (
* 获取sequence 序列号
*)  * @param @param sequenceName
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int getSeq(String sequenceName) ;
}

jdbc.java

 package com.jacezhu.dao;

 import java.util.ArrayList;
import java.util.List;
import java.util.Map; import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
import com.jacezhu.framework.connectUtil.jdbcUtl.PageModel; /**
*
* @Title: JdbcUtil.java  * @Package com.jacezhu.framework.connectUtil.jdbcUtl  * @Description: (JdbcUtil)  * @author 刘军
* @date 2016-3-17 下午11:04:19  * @version V1.0   */
public interface JdbcDao { /**
*
* @Title: insert  * @Description: (插入单挑数据)  * @param @param sql 查询sql
* @param @param obj 参数数组
* @param @param isGenerateKey (true false)
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean insert(String sql, Object[] obj);
/**
*
* @author 刘军
* @date 2016-3-19 下午2:23:42  * @version V1.0   * @Title: insertLines  * @Description: (新增)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int insertLines(String sql, Object[] obj);
/**
*
* @author 刘军
* @date 2016-3-19 下午2:05:19  * @version V1.0   * @Title: insert  * @Description: (新增)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean insertByList(String sql, List<Object> obj); /**
*
* @Title: delete  * @Description: (删除单挑数据)  * @param @param sql 删除sql
* @param @param obj 参数数组
* @param @param isGenerateKey (true false)
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean delete(String sql, Object[] obj);
/**
*
* @author 刘军
* @date 2016-3-19 下午2:19:20  * @version V1.0   * @Title: delete  * @Description: (删除单挑数据)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean delete(String sql,List<Object> obj); /**
*
* @Title: deleteALL  * @Description: (批量删除数据)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean deleteALL(String sql, Object[] obj);
/**
*
* @author 刘军
* @date 2016-3-19 下午2:20:56  * @version V1.0   * @Title: deleteALL  * @Description: (删除 批量删除 )  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean deleteALL(String sql,List<Object> obj);
/**
*
* @Title: update  * @Description: (更新单挑数据记录)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean update(String sql, Object[] obj);
/**
*
* @author 刘军
* @date 2016-3-19 下午2:21:45  * @version V1.0   * @Title: update  * @Description: (修改 )  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean update(String sql, List<Object> obj);
/**
*
* @Title: queryFrist  * @Description: (查询出第一条数据记录)  * @param @param tale
* @param @param objParams
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object queryFrist(String tale,Object[] objParams,ObjectMapper mapper);
/**
*
* @author 刘军
* @date 2016-3-19 上午9:41:06  * @version V1.0   * @Title: find  * @Description: (查询一条记录 )  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql, Object[] obj, ObjectMapper mapper);
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-14 下午1:18:51  * @version V1.0   * @Title: find  * @Description: (
* 查询一条记录
*)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql, List obj, ObjectMapper mapper);
/**
*
* @Title: query  * @Description: ( 查询所有的数据记录;并以list 集合(或者:Object 对象)返回 )  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, Object[] obj,
ObjectMapper mapper) ;
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午2:03:54  * @version V1.0   * @Title: query  * @Description: (
*
*)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, List obj,
ObjectMapper mapper) ;
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午11:19:59  * @version V1.0   * @Title: Count  * @Description: (
* 返回 统计count 数据的数量
*)  * @param @param sql
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public long Count(String sql);
/**
*
* @Title: CountNum  * @Description: ( select count(*)from table 的总数据条数)
* @param @param tableName (数据库表名)
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int CountNum (String tableName);
/**
*
* @Title: queryPageNumber  * @Description: (分页查询)  * @param @param pageNo 第几页
* @param @param pageSize 一页显示多少条数据
* @param @param table 查询哪个表
* 全表无条件查询
* {select * from ( tablea a,tableb b where a.id=b.id)limt numStrat,numStop}
* 全表 带条件模糊查询:
*SELECT * FROM demo a ,demo b WHERE a.id=b.id AND a.id LIKE "1%" LIMIT 0,15;
* @param @return    设定文件  * @return PageModel    返回类型  * @throws  */
public PageModel queryPageNumber(int pageNo, int pageSize,String table) ;
/**
*
* @Title: findSimpleResult  获取最后一条(单条)记录
* @Description: (查询单条记录)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return Map<String,Object>    返回类型  * @throws  */
public Map<String, Object> findSimpleResult(String sql, List<Object> params);
/**
*
* @author 刘军
* @date 2016-3-19 上午12:30:02  * @version V1.0   * @Title: findModeResult  查询多条记录
* @Description: (查询多条记录)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return List<Map<String,Object>>    返回类型  * @throws  */
public List<Map<String, Object>> findModeResult(String sql, List<Object> params);
/**
*
* @author 刘军
* @date 2016-3-19 上午8:43:07  * @version V1.0   * @Title: executeQuerySingle  * @Description: (SQL 查询将查询结果:一行一列)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object executeQuerySingle(String sql, Object[] params); /**
*
* @author 刘军
* @date 2016-3-19 上午9:08:05  * @version V1.0   * @Title: findSimpleRefResult  * @Description: (通过反射机制查询单条记录
* 如果需要调用:请调用jdbcBaseUtil
* )  * @param @param sql
* @param @param params
* @param @param cls
* @param @return    设定文件  * @return T    返回类型  * @throws  */
public <T> T findSimpleRefResult(String sql, List<Object> params,Class<T> cls) ;
/**
*
* @author 刘军
* @date 2016-3-19 上午9:13:39  * @version V1.0   * @Title: findMoreRefResult  * @Description: ( 通过反射机制查询多条记录)  * @param @param sql
* @param @param params
* @param @param cls
* @param @return    设定文件  * @return List<T>    返回类型  * @throws  */
public <T> List<T> findMoreRefResult(String sql, List<Object> params,
Class<T> cls);
/**
*
* @author 刘军
* @date 2016-3-19 上午11:03:06  * @version V1.0   * @Title: excuteQuery  * @Description: (获取结果集,并将结果放在List中)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return List<Object>    返回类型  * @throws  */
public List<Object> excuteQuery(String sql, Object[] params);
/**
*
* @author 刘军
* @date 2016-3-19 上午11:03:03  * @version V1.0   * @Title: executeQuery  * @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,)  * @param @param sql
* @param @param parameters
* @param @return    设定文件  * @return ArrayList    返回类型  * @throws  */
public ArrayList executeQuery(String sql, String[] parameters) ; /**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-17 上午11:33:28  * @version V1.0   * @Title: getSeq  * @Description: (
* 获取sequence 序列号
*)  * @param @param sequenceName
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int getSeq(String sequenceName);
}

BaseDaoImpl.java

 package com.jacezhu.dao.impl;

 import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map; import com.jacezhu.dao.BaseDaoI; import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; @Repository
public class BaseDaoImpl<T> implements BaseDaoI<T> { @Autowired
private SessionFactory sessionFactory; /**
* 获得当前事物的session
*
* @return org.hibernate.Session
*/
public Session getCurrentSession() {
return this.sessionFactory.getCurrentSession();
} @Override
public Serializable save(T o) {
if (o != null) {
return this.getCurrentSession().save(o);
}
return null;
} @Override
public T get(Class<T> c, Serializable id) {
return (T) this.getCurrentSession().get(c, id);
} @Override
public T get(String hql) {
Query q = this.getCurrentSession().createQuery(hql);
List<T> l = q.list();
if ((l != null) && (l.size() > 0)) {
return l.get(0);
}
return null;
} @Override
public T get(String hql, Map<String, Object> params) {
Query q = this.getCurrentSession().createQuery(hql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
List<T> l = q.list();
if ((l != null) && (l.size() > 0)) {
return l.get(0);
}
return null;
} @Override
public void delete(T o) {
if (o != null) {
this.getCurrentSession().delete(o);
}
} @Override
public void update(T o) {
if (o != null) {
this.getCurrentSession().update(o);
}
} @Override
public void saveOrUpdate(T o) {
if (o != null) {
this.getCurrentSession().saveOrUpdate(o);
}
} @Override
public List<T> find(String hql) {
Query q = this.getCurrentSession().createQuery(hql);
return q.list();
} @Override
public List<T> find(String hql, Map<String, Object> params) {
Query q = this.getCurrentSession().createQuery(hql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return q.list();
} @Override
public List<T> find(String hql, Map<String, Object> params, int page,
int rows) {
Query q = this.getCurrentSession().createQuery(hql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
} @Override
public List<T> find(String hql, int page, int rows) {
Query q = this.getCurrentSession().createQuery(hql);
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
} @Override
public Long count(String hql) {
Query q = this.getCurrentSession().createQuery(hql);
return (Long) q.uniqueResult();
} @Override
public Long count(String hql, Map<String, Object> params) {
Query q = this.getCurrentSession().createQuery(hql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return (Long) q.uniqueResult();
} @Override
public int executeHql(String hql) {
Query q = this.getCurrentSession().createQuery(hql);
return q.executeUpdate();
} @Override
public int executeHql(String hql, Map<String, Object> params) {
Query q = this.getCurrentSession().createQuery(hql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return q.executeUpdate();
} @Override
public List<Object[]> findBySql(String sql) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
return q.list();
} @Override
public List<Object[]> findBySql(String sql, int page, int rows) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
} @Override
public List<Object[]> findBySql(String sql, Map<String, Object> params) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return q.list();
} @Override
public List<Object[]> findBySql(String sql, Map<String, Object> params,
int page, int rows) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
} @Override
public int executeSql(String sql) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
return q.executeUpdate();
} @Override
public int executeSql(String sql, Map<String, Object> params) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return q.executeUpdate();
} @Override
public BigInteger countBySql(String sql) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
return (BigInteger) q.uniqueResult();
} @Override
public BigInteger countBySql(String sql, Map<String, Object> params) {
SQLQuery q = this.getCurrentSession().createSQLQuery(sql);
if ((params != null) && !params.isEmpty()) {
for (String key : params.keySet()) {
q.setParameter(key, params.get(key));
}
}
return (BigInteger) q.uniqueResult();
} @Override
public void refresh(T o) {
this.getCurrentSession().refresh(o); } @Override
public void merge(T o) {
this.getCurrentSession().merge(o);
}
}

JdbcBaseDaoImpl.java

 package com.jacezhu.dao.impl;

 import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.sql.DataSource; import org.springframework.stereotype.Repository;
import com.jacezhu.dao.JdbcBaseDao;
import com.jacezhu.framework.connectUtil.ConnUtil;
import com.jacezhu.framework.connectUtil.DataSourceConnUtil;
import com.jacezhu.framework.connectUtil.DruidDataSourceUtil;
import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
import com.jacezhu.framework.connectUtil.jdbcUtl.SqlParameter; @Repository
public class JdbcBaseDaoImpl implements JdbcBaseDao {
/**
* 获取连接
*/
static {
getConnection();
}
/**
* @author 刘军
* @date 2016-3-19 上午11:14:17  * @version V1.0   * @Title: getStatement  * @Description: ( )  * @param @return
* @param @throws SQLException    设定文件  * @return Connection    返回类型  * @throws  */
public Connection getStatement() throws SQLException {
Connection connection = null;
Statement statement = null;
// 仅当statement失效时才重新创建
if (statement == null || statement.isClosed() == true) {
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
return connection;
} /**
*
* @Title: getConnection  * @Description: (得到数据库连接)  * @param @return    设定文件  * @return Connection    返回类型  * @throws  */
public static Connection getConnection() {
Connection connection = null;
try {
/**
* 从 阿里巴巴 开源的数据库连接池中获取连接
*/
int dbType=0;
DataSource dataSource=DruidDataSourceUtil.getDataSource(dbType);
connection = dataSource.getConnection();
if (connection == null) {
/**
* 连接C3P0 连接池
*/
connection = DataSourceConnUtil.getConnection();
}
if (connection == null) {
/**
* 直接连接数据库
*/
connection = ConnUtil.getConn();
}
} catch (Exception e) {
e.printStackTrace();
}
return connection;
} /**
*
* @Title: update  * @Description: (更新:update)  * @param @param sql
* @param @param obj
* @param @param isGenerateKey
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean update(String sql, Object[] obj, boolean isGenerateKey) {
Connection conn = null;
PreparedStatement pstmt = null;
boolean bFlag = false;
try {
conn = JdbcBaseDaoImpl.getConnection();
pstmt = isGenerateKey ? conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS) : conn
.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
conn.setAutoCommit(false);//JDBC 事务管理
int i = pstmt.executeUpdate();
conn.commit();//JDBC 事务管理
if (i > 0)
bFlag = true;
} catch (SQLException ex) {
ex.printStackTrace();
try {
conn.rollback();//JDBC 事务管理
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
conn.close();
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return bFlag;
}
/**
*
* @Title: updateByPreparedStatement  增加、删除、改
* @Description: (增加、删除、改)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean updateByPreparedStatement(String sql, List<Object> params) {
boolean flag = false;
Connection connection = null;
PreparedStatement pstmt = null;
int result = -1;
try {
connection = JdbcBaseDaoImpl.getConnection();
pstmt = connection.prepareStatement(sql);
int index = 1;
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
result = pstmt.executeUpdate();
connection.commit();//JDBC 事务管理
flag = result > 0 ? true : false;
} catch (SQLException e) {
try {
connection.rollback();//JDBC 事务管理
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
pstmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} }
return flag;
} /**
* insert update delete SQL语句的执行的统一方法
*
* @param sql
* SQL语句
* @param params
* 参数数组,若没有参数则为null
* @return 受影响的行数
*/
public int executeUpdate(String sql, Object[] params) {
PreparedStatement preparedStatement = null;
// 受影响的行数
int affectedLine = 0;
Connection connection = null;
try {
// 获得连接
connection = JdbcBaseDaoImpl.getConnection();
// 调用SQL
preparedStatement = connection.prepareStatement(sql);
// 参数赋值
if (params != null) {
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
}
// 执行
affectedLine = preparedStatement.executeUpdate();
connection.commit();// 提交事务
} catch (SQLException e) {
System.out.println(e.getMessage());
try {
connection.rollback();//JDBC 事务管理
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
// 释放资源
close(connection, preparedStatement, null);
}
return affectedLine;
} /**
*
* @Title: query  * @Description: (这里用一句话描述这个方法的作用)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, Object[] obj,
ObjectMapper mapper) {
Object o = null;
List<Object> list = new ArrayList<Object>();
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JdbcBaseDaoImpl.getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
o = mapper.mapping(rs);
list.add(o);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return list;
}
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午1:54:42  * @version V1.0   * @Title: query  * @Description: (
*
*)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, List obj,
ObjectMapper mapper) {
Object o = null;
List<Object> list = new ArrayList<Object>();
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JdbcBaseDaoImpl.getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.size(); i++) {
pstmt.setObject(i + 1, obj.get(i));
}
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
o = mapper.mapping(rs);
list.add(o);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return list;
} /**
*
* @Title: returnTableCount  * @Description: ( select count(*)from table 的总数据条数)  * @param @param table
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int returnTableCount(String table){
String sql="select count(*) as counts from "+table+"";
Connection conn = null;
ResultSet resultSet = null;
Statement pstmt = null;
int count=0;
try {
conn = JdbcBaseDaoImpl.getConnection();
pstmt = conn.createStatement();
resultSet=pstmt.executeQuery(sql);
if(resultSet.next()){
count=resultSet.getInt("counts");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
resultSet.close();
pstmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return count; }
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午11:19:02  * @version V1.0   * @Title: Count  * @Description: (
* 统计有多少记录
*)  * @param @param sql
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public long Count(String sql){
if(sql==null || sql==""){
return (long)0;
}
Connection conn = null;
ResultSet resultSet = null;
Statement pstmt = null;
long count=0;
try {
conn = JdbcBaseDaoImpl.getConnection();
pstmt = conn.createStatement();
resultSet=pstmt.executeQuery(sql);
if(resultSet.next()){
count=resultSet.getInt("counts");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
resultSet.close();
pstmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return count; } /**
*
* @Title: findSimpleResult  获取最后一条(单条)记录
* @Description: (查询单条记录)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return Map<String,Object>    返回类型  * @throws  */
public Map<String, Object> findSimpleResult(String sql, List<Object> params) {
Map<String, Object> map = new HashMap<String, Object>();
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
int index = 1;
try {
connection = JdbcBaseDaoImpl.getConnection();
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();// 返回查询结果
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();
while (resultSet.next()) {
for (int i = 0; i < col_len; i++) {
String cols_name = metaData.getColumnName( i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
pstmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return map;
}
/**
* 获取结果集,并将结果放在List中
*
* @param sql
* SQL语句
* @return List 结果集
*/
public List<Object> excuteQuery(String sql, Object[] params) {
// 创建List
List<Object> list = new ArrayList<Object>();
Connection connection = null;
ResultSet rs = null;
// 创建ResultSetMetaData对象
ResultSetMetaData rsmd = null;
// 结果集列数
int columnCount = 0;
try {
// 获得连接
connection = JdbcBaseDaoImpl.getConnection();
// 执行SQL获得结果集
rs = executeQueryRS(sql, params);
// 将ResultSet的结果保存到List中
while (rs.next()) {
rsmd = rs.getMetaData();
// 获得结果集列数
columnCount = rsmd.getColumnCount();
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 1; i <= columnCount; i++) {
map.put(rsmd.getColumnLabel(i), rs.getObject(i));
}
list.add(map);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
// 关闭所有资源
try {
rs.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
} }
return list;
} /**
* SQL 查询将查询结果直接放入ResultSet中
*
* @param sql
* SQL语句
* @param params
* 参数数组,若没有参数则为null
* @return 结果集
*/
private ResultSet executeQueryRS(String sql, Object[] params) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 获得连接
connection = JdbcBaseDaoImpl.getConnection();
// 调用SQL
preparedStatement = connection.prepareStatement(sql);
// 参数赋值
if (params != null) {
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
}
// 执行
resultSet = preparedStatement.executeQuery(); } catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
resultSet.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} return resultSet;
} /**
*
* @Title: findModeResult  查询多条记录
* @Description: (查询多条记录)  * @param @param sql
* @param @param params
* @param @return
* @param @throws SQLException    设定文件  * @return List<Map<String,Object>>    返回类型  * @throws  */
public List<Map<String, Object>> findModeResult(String sql,
List<Object> params) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
int index = 1;
try {
connection = JdbcBaseDaoImpl.getConnection();
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
pstmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} return list;
} /**
* SQL 查询将查询结果:一行一列
*
* @param sql
* SQL语句
* @param params
* 参数数组,若没有参数则为null
* @return 结果集
*/
public Object executeQuerySingle(String sql, Object[] params) {
Object object = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 获得连接
connection = JdbcBaseDaoImpl.getConnection();
// 调用SQL
preparedStatement = connection.prepareStatement(sql);
// 参数赋值
if (params != null) {
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
}
// 执行
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
object = resultSet.getObject(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
close(connection, preparedStatement, resultSet);
}
return object;
} /**
*
* @Title: findSimpleRefResult  通过反射机制查询单条记录
* @Description: (通过反射机制查询单条记录)  * @param @param sql
* @param @param params
* @param @param cls
* @param @return
* @param @throws Exception    设定文件  * @return T    返回类型  * @throws  */
public <T> T findSimpleRefResult(String sql, List<Object> params,
Class<T> cls) {
T resultObject = null;
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
int index = 1;
try {
connection = JdbcBaseDaoImpl.getConnection();
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
// 通过反射机制创建一个实例
resultObject = cls.newInstance();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
Field field = cls.getDeclaredField(cols_name);
field.setAccessible(true); // 打开javabean的访问权限
field.set(resultObject, cols_value);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
pstmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resultObject; } /**
* 通过反射机制查询多条记录
*
* @param sql
* @param params
* @param cls
* @return
* @throws Exception
*/
public <T> List<T> findMoreRefResult(String sql, List<Object> params,
Class<T> cls) {
List<T> list = new ArrayList<T>();
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
int index = 1;
try {
connection = JdbcBaseDaoImpl.getConnection();
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
// 通过反射机制创建一个实例
T resultObject = cls.newInstance();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
Field field = cls.getDeclaredField(cols_name);
field.setAccessible(true); // 打开javabean的访问权限
field.set(resultObject, cols_value);
}
list.add(resultObject);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
pstmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} }
return list;
} /**
*
* @Title: find  * @Description: (查询一条记录)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql, Object[] obj, ObjectMapper mapper) {
Object o = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JdbcBaseDaoImpl.getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
o = mapper.mapping(rs);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return o;
}
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-14 下午1:17:28  * @version V1.0   * @Title: find  * @Description: (
* 查询一条记录
*)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql, List obj, ObjectMapper mapper) {
Object o = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JdbcBaseDaoImpl.getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.size(); i++) {
pstmt.setObject(i + 1, obj.get(i));
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
o = mapper.mapping(rs);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return o;
} /**
*
* @Title: executeQuery  统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源
* @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,这样可以直接关闭资源)  * @param @param sql
* @param @param parameters
* @param @return    设定文件  * @return ArrayList    返回类型  * @throws  */
@SuppressWarnings({ "rawtypes", "unchecked" })
public ArrayList executeQuery(String sql, String[] parameters) {
ArrayList results = new ArrayList();
// 定义需要的变量
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try {
// 获得连接
conn = JdbcBaseDaoImpl.getConnection();
ps = conn.prepareStatement(sql); if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
ps.setString(i + 1, parameters[i]);
}
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int column = rsmd.getColumnCount();
while (rs.next()) {
Object[] objects = new Object[column];
for (int i = 1; i <= column; i++) {
objects[i - 1] = rs.getObject(i);
}
results.add(objects);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return results;
} /**
*
* @Title: executeQuery  by statement
* @Description: (执行 查询sql 获取结果集)  * @param @param sql
* @param @return statement resultSet
* @param @throws SQLException    设定文件  * @return ResultSet    返回类型  * @throws  */
public ResultSet executeQuery(String sql) {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = null;
try {
connection = getStatement();
if (resultSet != null && resultSet.isClosed() == false) {
resultSet.close();
}
resultSet = null;
resultSet = statement.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
} finally { }
return resultSet;
} //-------------------------------------------对象化---------------
/**
* 将一条记录转成一个对象
*
* @param cls
* 泛型类型
* @param rs
* ResultSet对象
* @return 泛型类型对象
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
private static <T> T executeResultSet(Class<T> cls, ResultSet rs)
throws InstantiationException, IllegalAccessException, SQLException {
T obj = cls.newInstance();
ResultSetMetaData rsm = rs.getMetaData();
int columnCount = rsm.getColumnCount();
// Field[] fields = cls.getFields();
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
for (int j = 1; j <= columnCount; j++) {
String columnName = rsm.getColumnName(j);
if (fieldName.equalsIgnoreCase(columnName)) {
Object value = rs.getObject(j);
field.setAccessible(true);
field.set(obj, value);
break;
}
}
}
return obj;
} /**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-17 上午11:33:28  * @version V1.0   * @Title: getSeq  * @Description: (
* 获取sequence 序列号
*)  * @param @param sequenceName
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int getSeq(String sequenceName){
int count = 0;
Connection conn = getConnection();
String sql = "SELECT nextval('"+sequenceName+"');";
PreparedStatement ptmt = null;
ResultSet rs = null;
try {
ptmt = conn.prepareStatement(sql);
rs = ptmt.executeQuery();
while (rs.next()) {
count = rs.getInt(1);
}
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
ptmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} } return count;
} //----------------------存储过程调用------------------------------------------- /**
* 存储过程带有一个输出参数的方法
*
* @param sql
* 存储过程语句
* @param params
* 参数数组
* @param outParamPos
* 输出参数位置
* @param SqlType
* 输出参数类型
* @return 输出参数的值
*/
public Object executeQuery(String sql, Object[] params, int outParamPos,
int SqlType) {
Connection connection = null;
Statement statement = null;
Object object = null;
CallableStatement callableStatement = null;
try {
connection = JdbcBaseDaoImpl.getConnection();
// 调用存储过程
callableStatement = connection.prepareCall(sql);
// 给参数赋值
if (params != null) {
for (int i = 0; i < params.length; i++) {
callableStatement.setObject(i + 1, params[i]);
}
}
// 注册输出参数
callableStatement.registerOutParameter(outParamPos, SqlType);
// 执行
callableStatement.execute();
// 得到输出参数
object = callableStatement.getObject(outParamPos);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
// 释放资源
closeAll(connection, null, callableStatement, null);
}
return object;
} /**
* 执行不返回结果集的存储过程
*
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @throws ClassNotFoundException
* @throws SQLException
*/
public void executeNonQuery(String sql, SqlParameter... params) {
Connection con = null;
CallableStatement cs = null;
try {
con = getConnection();
cs = con.prepareCall(sql);
setSqlParameter(cs, params);
cs.executeUpdate();
getSqlParameter(cs, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, cs, null);
}
} /**
* 执行Insert语句,返回Insert成功之后标识列的值
*
* @param sql
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public int executeIdentity(String sql) {
int identity = -1;
Connection con = null;
Statement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.createStatement();
ps.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
rs = ps.getGeneratedKeys();
if (rs.next()) {
// identity = rs.getInt("GENERATED_KEYS");
identity = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, ps, null);
}
return identity;
}
/**
* 执行不返回结果集的存储过程
*
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @throws ClassNotFoundException
* @throws SQLException
*/
public void executeNonQuery1(String sql, SqlParameter... params) {
Connection con = null;
CallableStatement cs = null;
try {
con = getConnection();
cs = con.prepareCall(sql);
setSqlParameter(cs, params);
cs.executeUpdate();
getSqlParameter(cs, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, cs, null);
}
}
/**
* 执行返回聚合函数的操作
*
* @param sql
* 含有聚合函数的SQL语句
* @return 聚合函数的执行结果
* @throws SQLException
* @throws ClassNotFoundException
*/
public int executeScalar(String sql) {
int result = -1;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
result = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, ps, rs);
}
return result;
}
/**
* 执行返回泛型集合的SQL语句
*
* @param cls
* 泛型类型
* @param sql
* 查询SQL语句
* @return 泛型集合
* @throws ClassNotFoundException
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> List<T> executeList(Class<T> cls, String sql) {
List<T> list = new ArrayList<T>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
T obj = executeResultSet(cls, rs);
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, ps, rs);
}
return list;
}
/**
* 执行返回泛型集合的存储过程
*
* @param cls
* 泛型类型
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @return 泛型集合
* @throws ClassNotFoundException
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> List<T> executeList(Class<T> cls, String sql,
SqlParameter... params) {
List<T> list = new ArrayList<T>();
Connection con = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
con = getConnection();
cs = con.prepareCall(sql);
setSqlParameter(cs, params);
rs = cs.executeQuery();
while (rs.next()) {
T obj = executeResultSet(cls, rs);
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, cs, rs);
}
return list;
}
/**
* 执行返回泛型类型对象的SQL语句
*
* @param cls
* 泛型类型
* @param sql
* SQL语句
* @return 泛型类型对象
* @throws SQLException
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> T executeEntity(Class<T> cls, String sql) {
T obj = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
obj = executeResultSet(cls, rs);
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, ps, rs);
}
return obj;
}
/**
* 执行返回泛型类型对象的存储过程
*
* @param cls
* 泛型类型
* @param sql
* SQL语句
* @param params
* 存储过程参数
* @return 泛型类型对象
* @throws SQLException
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> T executeEntity(Class<T> cls, String sql,
SqlParameter... params) {
T obj = null;
Connection con = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
con = getConnection();
cs = con.prepareCall(sql);
setSqlParameter(cs, params);
rs = cs.executeQuery();
while (rs.next()) {
obj = executeResultSet(cls, rs);
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close3(con, cs, rs);
}
return obj;
} /**
* 设置存储过程参数名称,参数值,参数方向
*
* @param cs
* @param params
* @throws SQLException
*/
private void setSqlParameter(CallableStatement cs,
SqlParameter... params) throws SQLException {
if (params != null) {
for (SqlParameter param : params) {
if (param.OutPut) {
String paramName = param.Name;
if (paramName == null || paramName.equals("")) {
cs.registerOutParameter(1, param.Type);// 设置返回类型参数
} else {
cs.registerOutParameter(paramName, param.Type);// 设置输出类型参数
}
} else {
cs.setObject(param.Name, param.Value);// 设置输入类型参数
}
}
}
}
/**
* 得到存储过程参数执行结果
*
* @param cs
* @param params
* @throws SQLException
*/
private void getSqlParameter(CallableStatement cs,
SqlParameter... params) throws SQLException {
for (SqlParameter param : params) {
if (param.OutPut) {
String paramName = param.Name;
if (paramName == null || paramName.equals("")) {
param.Value = cs.getObject(1);// 返回类型参数值
} else {
param.Value = cs.getObject(paramName);// 输出类型参数值
}
}
}
} /**
*
* @Title: executeUpdate  by statement
* @Description: (更新结果集)  * @param @param sql
* @param @return
* @param @throws SQLException    设定文件  * @return int    返回类型  * @throws  */
@SuppressWarnings("null")
public int executeUpdate(String sql) {
Statement statement = null;
Connection connection = null;
int result = 0;
try {
connection = getStatement();
result = statement.executeUpdate(sql);
connection.commit();//JDBC 事务管理
} catch (Exception e) {
e.printStackTrace();
try {
connection.rollback();//JDBC 事务管理
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} }
return result;
} //-----------------------资源关闭---------------------------------------------
/**
* 关闭所有资源
*
* @param statement
*/
private void closeAll(Connection connection,
PreparedStatement preparedStatement,
CallableStatement callableStatement, ResultSet resultSet) {
// 关闭结果集对象
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
} // 关闭PreparedStatement对象
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
} // 关闭CallableStatement 对象
if (callableStatement != null) {
try {
callableStatement.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
} // 关闭Connection 对象
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
} /**
*
* @Title: close  * @Description: (关闭所有的连接)  * @param @throws SQLException    设定文件  * @return void    返回类型  * @throws  */
public void close(Connection connection, Statement statement,
ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
resultSet = null;
}
if (statement != null) {
statement.close();
statement = null;
}
if (connection != null) {
connection.close();
connection = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭JDBC对象,释放资源。
*
* @param con
* 连接对象
* @param ps
* 命令对象
* @param rs
* 结果集对象
* @throws SQLException
*/
private static void close3(Connection con, Statement ps, ResultSet rs) {
try {
rs.close();
if (rs != null) { rs = null;
}
if (ps != null) {
ps.close();
ps = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
// Auto-generated catch block
e.printStackTrace();
}
} //--------------------main 方法----------------------------------------------
/**
* 测试 连接是否成功
*
* @param args
*/
public static void main(String[] args) {
getConnection();
} }

JdbcDaoImpl.java

 package com.jacezhu.dao.impl;

 import java.util.ArrayList;
import java.util.List;
import java.util.Map; import com.jacezhu.dao.JdbcBaseDao;
import com.jacezhu.dao.JdbcDao;
import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
import com.jacezhu.framework.connectUtil.jdbcUtl.PageModel;
import com.jacezhu.model.demo.vo.Demo;
import com.jacezhu.service.demo.impl.DemoMapper; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class JdbcDaoImpl extends Object implements JdbcDao{
@Autowired
private JdbcBaseDaoImpl jdbcBaseUtil =new JdbcBaseDaoImpl(); public JdbcBaseDaoImpl getJdbcBaseUtil() {
return jdbcBaseUtil;
}
public void setJdbcBaseUtil(JdbcBaseDaoImpl jdbcBaseUtil) {
this.jdbcBaseUtil = jdbcBaseUtil;
}
/**
*
* @Title: insert  * @Description: (插入单挑数据)  * @param @param sql 查询sql
* @param @param obj 参数数组
* @param @param isGenerateKey (true false)
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean insert(String sql, Object[] obj){ return jdbcBaseUtil.update(sql, obj, false);
}
/**
*
* @author 刘军
* @date 2016-3-19 下午2:23:42  * @version V1.0   * @Title: insertLines  * @Description: (新增)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int insertLines(String sql, Object[] obj){ return jdbcBaseUtil.executeUpdate(sql, obj);
}
/**
*
* @author 刘军
* @date 2016-3-19 下午2:05:19  * @version V1.0   * @Title: insert  * @Description: (新增)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean insertByList(String sql, List<Object> obj){ return jdbcBaseUtil.updateByPreparedStatement(sql, obj);
} /**
*
* @Title: delete  * @Description: (删除单挑数据)  * @param @param sql 删除sql
* @param @param obj 参数数组
* @param @param isGenerateKey (true false)
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean delete(String sql, Object[] obj){ return jdbcBaseUtil.update(sql, obj, false);
}
/**
*
* @author 刘军
* @date 2016-3-19 下午2:19:20  * @version V1.0   * @Title: delete  * @Description: (删除单挑数据)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean delete(String sql,List<Object> obj){ return jdbcBaseUtil.updateByPreparedStatement(sql, obj);
} /**
*
* @Title: deleteALL  * @Description: (批量删除数据)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean deleteALL(String sql, Object[] obj){
StringBuffer sbStr = new StringBuffer();
for (int i = 0; i < obj.length; i++) {
sbStr.append("?,");
}
String sqls =sql+"("+ sbStr.substring(0, sbStr.length() - 1) + ")";
return jdbcBaseUtil.update(sqls, obj, false);
}
/**
*
* @author 刘军
* @date 2016-3-19 下午2:20:56  * @version V1.0   * @Title: deleteALL  * @Description: (删除 批量删除 )  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean deleteALL(String sql,List<Object> obj){
StringBuffer sbStr = new StringBuffer();
for (int i = 0; i < obj.size(); i++) {
sbStr.append("?,");
}
String sqls =sql+"("+ sbStr.substring(0, sbStr.length() - 1) + ")";
return jdbcBaseUtil.updateByPreparedStatement(sqls, obj);
}
/**
*
* @Title: update  * @Description: (更新单挑数据记录)  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean update(String sql, Object[] obj){ return jdbcBaseUtil.update(sql, obj, false);
}
/**
*
* @author 刘军
* @date 2016-3-19 下午2:21:45  * @version V1.0   * @Title: update  * @Description: (修改 )  * @param @param sql
* @param @param obj
* @param @return    设定文件  * @return boolean    返回类型  * @throws  */
public boolean update(String sql, List<Object> obj){ return jdbcBaseUtil.updateByPreparedStatement(sql, obj);
}
/**
*
* @Title: queryFrist  * @Description: (查询出第一条数据记录)  * @param @param tale
* @param @param objParams
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object queryFrist(String tale,Object[] objParams,ObjectMapper mapper){ String sql = "select * from "+tale+"";
Object[] obj = objParams;
return (Object) query(sql, obj, mapper).get(0);
}
/**
*
* @author 刘军
* @date 2016-3-19 上午9:41:06  * @version V1.0   * @Title: find  * @Description: (查询一条记录 )  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql, Object[] obj, ObjectMapper mapper){
return jdbcBaseUtil. find( sql, obj, mapper) ; } /**
*
* @author 刘军
* @date 2016-3-19 上午9:41:06  * @version V1.0   * @Title: find  * @Description: (查询一条记录 )  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object find(String sql,List obj,ObjectMapper mapper){ return jdbcBaseUtil. find( sql, obj, mapper) ;
}
/**
*
* @Title: query  * @Description: ( 查询所有的数据记录;并以list 集合(或者:Object 对象)返回 )  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, Object[] obj,
ObjectMapper mapper) { return jdbcBaseUtil.query(sql, obj, mapper);
}
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午1:55:08  * @version V1.0   * @Title: query  * @Description: (
*查询所有的数据记录;并以list 集合(或者:Object 对象)返回
*)  * @param @param sql
* @param @param obj
* @param @param mapper
* @param @return    设定文件  * @return List<? extends Object>    返回类型  * @throws  */
public List<? extends Object> query(String sql, List obj,
ObjectMapper mapper) { return jdbcBaseUtil.query(sql, obj, mapper);
}
/**
*
* @Title: CountNum  * @Description: ( select count(*)from table 的总数据条数)
* @param @param tableName (数据库表名)
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int CountNum (String tableName){
return jdbcBaseUtil.returnTableCount(tableName);
} /**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-12 下午11:19:59  * @version V1.0   * @Title: Count  * @Description: (
* 返回 统计count 数据的数量
*)  * @param @param sql
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public long Count(String sql){
return jdbcBaseUtil.Count(sql);
};
/**
*
* @Title: queryPageNumber  * @Description: (分页查询)  * @param @param pageNo 第几页
* @param @param pageSize 一页显示多少条数据
* @param @param table 查询哪个表
* 全表无条件查询
* {select * from ( tablea a,tableb b where a.id=b.id)limt numStrat,numStop}
* 全表 带条件模糊查询:
*SELECT * FROM demo a ,demo b WHERE a.id=b.id AND a.id LIKE "1%" LIMIT 0,15;
* @param @return    设定文件  * @return PageModel    返回类型  * @throws  */
public PageModel queryPageNumber(int pageNo, int pageSize,String table) {
//oracle 分页
//String sql="select * from (select j.*,rownum rn from (select * from "+table+") j where rownum<=?) where rn>?";
//mysql 分页
String sql="SELECT * FROM "+table+" LIMIT ?,?;";
return queryPageNumber( pageNo, pageSize, table, sql); } @SuppressWarnings({ "rawtypes", "unchecked" })
public PageModel queryPageNumber(int pageNo, int pageSize,String table,String sql) {
int countTotal=CountNum(table);
Object[] obj = {(pageNo - 1) * pageSize, pageNo * pageSize};
List<Demo> list = (List<Demo>) query(sql, obj,new DemoMapper());
PageModel pagemodel = new PageModel();
pagemodel.setPageNo(pageNo);
pagemodel.setPageSize(pageSize);
pagemodel.setList(list);
pagemodel.setTotalRecords(countTotal);
if(pageSize!=0){
pagemodel.setCountPageNo(countTotal/pageSize);
}
return pagemodel; }
/**
*
* @Title: findSimpleResult  获取最后一条(单条)记录
* @Description: (查询单条记录)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return Map<String,Object>    返回类型  * @throws  */
public Map<String, Object> findSimpleResult(String sql, List<Object> params){ return jdbcBaseUtil.findSimpleResult(sql, params);
}
/**
*
* @author 刘军
* @date 2016-3-19 上午12:30:02  * @version V1.0   * @Title: findModeResult  查询多条记录
* @Description: (查询多条记录)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return List<Map<String,Object>>    返回类型  * @throws  */
public List<Map<String, Object>> findModeResult(String sql, List<Object> params){
return jdbcBaseUtil.findModeResult(sql,params);
}
/**
*
* @author 刘军
* @date 2016-3-19 上午8:43:07  * @version V1.0   * @Title: executeQuerySingle  * @Description: (SQL 查询将查询结果:一行一列)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return Object    返回类型  * @throws  */
public Object executeQuerySingle(String sql, Object[] params){
return jdbcBaseUtil.executeQuerySingle(sql, params);
} /**
*
* @author 刘军
* @date 2016-3-19 上午9:08:05  * @version V1.0   * @Title: findSimpleRefResult  * @Description: (通过反射机制查询单条记录)  * @param @param sql
* @param @param params
* @param @param cls
* @param @return    设定文件  * @return T    返回类型  * @throws  */
public <T> T findSimpleRefResult(String sql, List<Object> params,Class<T> cls) { //return JdbcBaseUtil.findSimpleRefResult(sql, params, cls);
return null;
}
/**
*
* @author 刘军
* @date 2016-3-19 上午9:13:39  * @version V1.0   * @Title: findMoreRefResult  * @Description: ( 通过反射机制查询多条记录)  * @param @param sql
* @param @param params
* @param @param cls
* @param @return    设定文件  * @return List<T>    返回类型  * @throws  */
public <T> List<T> findMoreRefResult(String sql, List<Object> params,
Class<T> cls) {
return jdbcBaseUtil.findMoreRefResult(sql, params, cls);
}
/**
*
* @author 刘军
* @date 2016-3-19 上午11:03:06  * @version V1.0   * @Title: excuteQuery  * @Description: (获取结果集,并将结果放在List中)  * @param @param sql
* @param @param params
* @param @return    设定文件  * @return List<Object>    返回类型  * @throws  */
public List<Object> excuteQuery(String sql, Object[] params){
return jdbcBaseUtil.excuteQuery( sql, params);
}
/**
*
* @author 刘军
* @date 2016-3-19 上午11:03:03  * @version V1.0   * @Title: executeQuery  * @Description: (统一的select语句,为了能够访问结果集,将结果集放入ArrayList,)  * @param @param sql
* @param @param parameters
* @param @return    设定文件  * @return ArrayList    返回类型  * @throws  */
public ArrayList executeQuery(String sql, String[] parameters){
return jdbcBaseUtil.executeQuery( sql, parameters);
} /**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-17 上午11:33:28  * @version V1.0   * @Title: getSeq  * @Description: (
* 获取sequence 序列号
*)  * @param @param sequenceName
* @param @return    设定文件  * @return int    返回类型  * @throws  */
public int getSeq(String sequenceName){
return jdbcBaseUtil.getSeq(sequenceName);
}
}

六:实例参考

控制层顶层:BaseController.java

 package com.jacezhu.controller.base;

 import java.text.SimpleDateFormat;
import java.util.Date; import com.jacezhu.framework.utils.StringEscapeEditor; import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/base")
public class BaseController { protected int page = 1;// 当前页
protected int rows = 10;// 每页显示记录数
protected String sort;// 排序字段
protected String order = "asc";// asc/desc protected String ids;// 主键集合,逗号分割 @InitBinder
public void initBinder(ServletRequestDataBinder binder) {
/**
* 自动转换日期类型的字段格式
*/
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true)); /**
* 防止XSS攻击
*/
binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
} /**
* 用户跳转JSP页面
*
* 此方法不考虑权限控制
* produces = "text/html;charset=UTF-8"
* @param folder
* 路径
* @param jspName
* JSP名称(不加后缀)
* @return 指定JSP页面
*/
@RequestMapping("/{folder}/{jspName}")
public String redirectJsp(@PathVariable String folder, @PathVariable String jspName) {
return "/" + folder + "/" + jspName;
} }

控制层实现层:StudentinfoController.java

 package com.jacezhu.controller.businessCore.CustomerManagement;

 import javax.servlet.http.HttpServletRequest;

 import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.jacezhu.controller.base.BaseController;
import com.jacezhu.framework.utils.BeanUtil.dateUtils.DateUtils;
import com.jacezhu.model.base.pageModel.Grid;
import com.jacezhu.model.base.pageModel.Json;
import com.jacezhu.model.base.pageModel.PageFilter;
import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo;
import com.jacezhu.model.businessCore.CustomerManagement.vo.StudentInfo;
import com.jacezhu.service.businessCore.CustomerManagement.StudentinfoServiceI;
/**
*
* @Title: StudentinfoController.java  * @Package com.jacezhu.controller.businessCore.CustomerManagement  * @Description: ( 客户管理:学生信息管理)  * @author 刘军
* @date 2016-3-20 下午3:59:30  * @version V1.0   */
@Controller
@RequestMapping("/studentinfo")
public class StudentinfoController extends BaseController{
@Autowired
private StudentinfoServiceI studentinfoServiceI; @RequestMapping("/manager")
public String manager() {
return "/businessCore/customer/student";
}
/**
*
* @author 刘军
* @date 2016-3-20 下午10:56:25  * @version V1.0   * @Title: dataGrid  * @Description: (获取列表数据: )  * @param @param studentInfo
* @param @param ph
* @param @return    设定文件  * @return Grid    返回类型  * @throws  */
@RequestMapping("/dataGrid")
@ResponseBody
public Grid dataGrid(StudentInfo studentInfo, PageFilter ph) {
Grid grid = new Grid();
grid.setRows(studentinfoServiceI.dataGrid(studentInfo, ph));
grid.setTotal(studentinfoServiceI.count(studentInfo, ph));
return grid;
}
//------------start----学生签到管理:查询学生信息-------------------------------
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-11 下午5:27:42  * @version V1.0   * @Title: dataGridToReport  * @Description: (
* 查询未签到的学生信息
*)  * @param @param studentInfo
* @param @param ph
* @param @return    设定文件  * @return Grid    返回类型  * @throws  */
@RequestMapping("/dataGridToReport")
@ResponseBody
public Grid dataGridToReport(StudentInfo studentInfo, PageFilter ph) {
Grid grid = new Grid();
grid.setRows(studentinfoServiceI.dataGridToReport(studentInfo, ph));
grid.setTotal(studentinfoServiceI.countToReport(studentInfo, ph));
return grid;
}
/**
*
* @author liujun<1136808529@qq.coom>
* @date 2016-5-11 下午5:29:16  * @version V1.0   * @Title: dataGridIsReported  * @Description: (
* 已经签到的学生信息
*)  * @param @param studentInfo
* @param @param ph
* @param @return    设定文件  * @return Grid    返回类型  * @throws  */
@RequestMapping("/dataGridIsReported")
@ResponseBody
public Grid dataGridIsReported(StudentInfo studentInfo, PageFilter ph) {
Grid grid = new Grid();
grid.setRows(studentinfoServiceI.dataGridIsReported(studentInfo, ph));
grid.setTotal(studentinfoServiceI.countIsReported(studentInfo, ph));
return grid;
}
//---------end-------学生签到管理:查询学生信息-------------------------------
/**
*
* @author 刘军
* @date 2016-3-20 下午11:01:23  * @version V1.0   * @Title: addPage  * @Description: (显示:添加页面)  * @param @return    设定文件  * @return String    返回类型  * @throws  */
@RequestMapping("/addPage")
public String addPage() {
return "/businessCore/customer/studentInfoAdd";
}
@RequestMapping("/addStuInfo")
@ResponseBody
public Json add(StudentInfo studentInfo) {
Json j = new Json();
try {
studentinfoServiceI.add(studentInfo);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
} @RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
try {
studentinfoServiceI.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
} @RequestMapping("/get")
@ResponseBody
public TStudentinfo get(Long id) {
return studentinfoServiceI.get(id);
}
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request, Long id) {
TStudentinfo studentInfo = studentinfoServiceI.get(id);
request.setAttribute("studentInfo", studentInfo);
return "/businessCore/customer/studentInfoEdit";
} @RequestMapping("/edit")
@ResponseBody
public Json edit(StudentInfo studentInfo ) {
Json j = new Json();
try {
TStudentinfo studentinfos=new TStudentinfo();
BeanUtils.copyProperties(studentInfo, studentinfos);
studentinfos.setStuapplyTime(DateUtils.formatDate(studentInfo.getStuapplyTime(),DateUtils.FORMAT_SHORT)); studentinfoServiceI.edit(studentinfos);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/viewPage")
public String viewPage(HttpServletRequest request, Long id) {
TStudentinfo studentInfo = studentinfoServiceI.get(id);
request.setAttribute("studentInfo", studentInfo);
return "/businessCore/customer/studentInfoView";
} }

服务层 StudentinfoServiceI.java

 package com.jacezhu.service.businessCore.CustomerManagement;

 import java.util.List;

 import com.jacezhu.model.base.pageModel.PageFilter;
import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo;
import com.jacezhu.model.businessCore.CustomerManagement.vo.StudentInfo;
import com.jacezhu.model.businessCore.CustomerManagement.vo.VStudentinfo; public interface StudentinfoServiceI { public List<TStudentinfo> dataGrid(StudentInfo studentInfo, PageFilter ph);
public Long count(StudentInfo studentInfo, PageFilter ph);
//---------学生签到管理 查询学生信息------------
/** 查询 未签到的学生信息
*/
public List<VStudentinfo> dataGridToReport(StudentInfo studentInfo, PageFilter ph);
public Long countToReport(StudentInfo studentInfo, PageFilter ph); /**查询已经签到的学生信息
*/
public List<TStudentinfo> dataGridIsReported(StudentInfo studentInfo, PageFilter ph);
public Long countIsReported(StudentInfo studentInfo, PageFilter ph);
//----------------------
public void add(StudentInfo studentInfo);
public void delete(Long id);
public TStudentinfo get(Long id);
public void edit(TStudentinfo studentInfo); }

服务实现层:StudentinfoServiceImpl.java

 package com.jacezhu.service.businessCore.CustomerManagement.impl;

 import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Httpssion; import com.jacezhu.dao.BaseDaoI;
import com.jacezhu.dao.impl.JdbcDaoImpl;
import com.jacezhu.framework.constant.GlobalConstant;
import com.jacezhu.model.base.pageModel.PageFilter;
import com.jacezhu.model.base.pageModel.SessionInfo;
import com.jacezhu.model.businessCore.CustomerManagement.THisStudentinfo;
import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo;
import com.jacezhu.model.businessCore.CustomerManagement.mapper.TStudentInfoMapper;
import com.jacezhu.model.businessCore.CustomerManagement.mapper.VStudentinfoMapper;
import com.jacezhu.model.businessCore.CustomerManagement.vo.StudentInfo;
import com.jacezhu.model.businessCore.CustomerManagement.vo.VStudentinfo;
import com.jacezhu.service.businessCore.CustomerManagement.StudentinfoServiceI; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentinfoServiceImpl implements StudentinfoServiceI{
@Autowired
private BaseDaoI<TStudentinfo> tstudentInfoDao ;
@Autowired
private BaseDaoI<StudentInfo> studentInfoDao ; @Autowired
private BaseDaoI<THisStudentinfo> hisStudentInfoDao ;
//----使用spring专属的方式获取session
@Autowired
private HttpSession session;
@Autowired
private HttpServletRequest request;
//引入 jsbc
private JdbcDaoImpl daoImpl=new JdbcDaoImpl() ; public JdbcDaoImpl getDaoImpl() {
return daoImpl;
} public void setDaoImpl(JdbcDaoImpl daoImpl) {
this.daoImpl = daoImpl;
}
/**
* datagrid 列表数据查询
*/
@Override
public List<TStudentinfo> dataGrid(StudentInfo studentInfo, PageFilter ph) {
List<TStudentinfo> ul = new ArrayList<TStudentinfo>();
Map<String, Object> params = new HashMap<String, Object>();
String hql = " from TStudentinfo t ";
List<TStudentinfo> l = tstudentInfoDao.find(hql + whereHql(studentInfo, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
for (TStudentinfo t : l) {
TStudentinfo u = new TStudentinfo();
BeanUtils.copyProperties(t, u);
ul.add(u);
}
return ul;
} @Override
public Long count(StudentInfo studentInfo, PageFilter ph) {
Map<String, Object> params = new HashMap<String, Object>();
String hql = " from TStudentinfo t ";
return tstudentInfoDao.count("select count(*) " + hql + whereHql(studentInfo, params), params);
} /**
*
* @author 刘军
* @date 2016-4-16 下午11:17:07  * @version V1.0   * @Title: whereHql  * @Description: ( datagrid 拼接查询语句 )  * @param @param studentInfo
* @param @param params
* @param @return    设定文件  * @return String    返回类型  * @throws  */
private String whereHql(StudentInfo studentInfo, Map<String, Object> params) {
String hql = "";
if (studentInfo != null) {
hql += " where 1=1 and stustatus=1 ";
if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
hql += " and t.stuname like :stuname";
params.put("stuname", "%%" + studentInfo.getStuname() + "%%");
}
if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
hql += " and t.stuenglishName like :stuenglishName";
params.put("stuenglishName", "%%" + studentInfo.getStuenglishName() + "%%");
}
if (studentInfo.getStuapplyTimeStart() != null) {
hql += " and t.stuapplyTime >= :stuapplyTimeStart";
params.put("stuapplyTimeStart", studentInfo.getStuapplyTimeStart());
}
if (studentInfo.getStuapplyTimeEnd() != null) {
hql += " and t.stuapplyTime <= :stuapplyTimeEnd";
params.put("stuapplyTimeEnd", studentInfo.getStuapplyTimeEnd());
}
}
return hql;
}
/**
*
* @author 刘军
* @date 2016-4-16 下午11:18:25  * @version V1.0   * @Title: orderHql  * @Description: (datagrid 拼接 排序)  * @param @param ph
* @param @return    设定文件  * @return String    返回类型  * @throws  */
private String orderHql(PageFilter ph) {
String orderString = "";
if ((ph.getSort() != null) && (ph.getOrder() != null)) {
orderString = " order by t." + ph.getSort() + "" + ph.getOrder();
}
return orderString;
}
//----------------------学生签到管理:查询未签到学生信息-ToReport------------------------------
@Override
public List<VStudentinfo> dataGridToReport(StudentInfo studentInfo, PageFilter ph) {
List<VStudentinfo> listJdbc=getSql(studentInfo,ph);
return listJdbc;
} @Override
public Long countToReport(StudentInfo studentInfo, PageFilter ph) {
List<Object> obj=new ArrayList<Object>();
String sql = " select count(*) as counts from t_studentinfo ts where 1=1 ";
//----------拼写:查询条件
if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
sql += " and ts.stuname like '%"+ studentInfo.getStuname()+"%'";
}
if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
sql += " and ts.stuenglishName like '%" +studentInfo.getStuenglishName()+"%'";
}
if (studentInfo.getStuapplyTimeStart() != null) {
sql += " and ts.stuapplyTime >= '"+studentInfo.getStuapplyTimeStart()+"'";
}
if (studentInfo.getStuapplyTimeEnd() != null) {
sql += " and ts.stuapplyTime <= '"+studentInfo.getStuapplyTimeEnd()+"'";
}
return daoImpl.Count(sql);
} //------jdbc 查询 @SuppressWarnings("unchecked")
private List<VStudentinfo> getSql(StudentInfo studentInfo, PageFilter ph){
List<VStudentinfo> list=new ArrayList<VStudentinfo>();
String sql= " SELECT ts.stuid AS stuid ,"
+" ts.stuname AS stuname ,"
+" ts.stuenglishName AS stuenglishName,"
+" ts.stusex AS stusex ,"
+" ds.value AS sexname,"
+" ts.stubrithday AS stubrithday,"
+" ts.stuschool AS stuschool ,"
+" ts.stugrade AS stugrade,"
+" ts.studepartment AS studepartment,"
+" dp.value AS studepartmentname ,"
+" ts.stuRegistration AS stuRegistration,"
+" tr.value AS registrationname,"
+" ts.stupickUp AS stupickUp,"
+" dpk.value AS pickUpName,"
+" ts.stuattention AS stuattention,"
+" ts.stuhobby AS stuhobby ,"
+" ts.stuavoidFood AS stuavoidFood,"
+" ts.stuallergySmptoms AS stuallergySmptoms,"
+" ts.stuacuteillness AS stuacuteillness,"
+" ts.stuotherInfo AS stuotherInfo,"
+" ts.prId AS prId,"
+" tp.prName AS prName,"
+" ts.stustatus AS stustatus,"
+" dst.value AS stustatusName ,"
+" ts.stuapplyTime AS stuapplyTime,"
+" ts.userid AS userid ,su.name AS userName,"
+" ts.druguse AS druguse "
+" FROM t_studentinfo ts , t_dic_sex ds , t_dic_partment dp, t_dic_pickup dpk,"
+" t_dic_status dst, t_dic_registration tr , sys_user su, t_parentsinfo tp "
+" WHERE ts.stusex =ds.id AND ts.studepartment=dp.id AND ts.stuRegistration=tr.id "
+" AND ts.stupickUp=dpk.id AND ts.stustatus=dst.id AND ts.userid = su.id AND ts.prId=tp.prId "
+" 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)) ) ";
//------拼接查询条件
List<Object> obj=new ArrayList<Object>();
//----------拼写:查询条件
if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
sql += " and ts.stuname like ? ";
obj.add( "%" + studentInfo.getStuname() + "%");
}
if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
sql += " and ts.stuenglishName like ? ";
obj.add( "%" + studentInfo.getStuenglishName() + "%");
}
if (studentInfo.getStuapplyTimeStart() != null) {
sql += " and ts.stuapplyTime >= ? ";
obj.add( studentInfo.getStuapplyTimeStart());
}
if (studentInfo.getStuapplyTimeEnd() != null) {
sql += " and ts.stuapplyTime <= ? ";
obj.add( studentInfo.getStuapplyTimeEnd());
}
//---------- order by
if(ph.getSort()!= null && ph.getOrder()!=null){
sql += " order by ts." + ph.getSort() + "" + ph.getOrder();
}
//----------- limit 分页
sql += " LIMIT "+((ph.getPage() - 1) * ph.getRows())+","+ ph.getPage() * ph.getRows() ; list=(List<VStudentinfo>)daoImpl.query(sql , obj, new VStudentinfoMapper());
return list;
} /**
*
* @author 刘军
* @date 2016-4-16 下午11:17:07  * @version V1.0   * @Title: whereHql  * @Description: ( datagrid 拼接查询语句 )  * @param @param studentInfo
* @param @param params
* @param @return    设定文件  * @return String    返回类型  * @throws  */
private String whereHqlToReport(StudentInfo studentInfo, Map<String, Object> params) {
String hql = "";
if (studentInfo != null) {
hql += " where 1=1 and t.stustatus=1 and t.stuid not in"
+ " (select tr.stuid from TReportsorexit tr "
+ " WHERE tr.reportstime BETWEEN TIMESTAMP(DATE(SYSDATE())) AND TIMESTAMP(ADDDATE(DATE(SYSDATE()),1)) ) ";
if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
hql += " and t.stuname like :stuname";
params.put("stuname", "%%" + studentInfo.getStuname() + "%%");
}
if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
hql += " and t.stuenglishName like :stuenglishName";
params.put("stuenglishName", "%%" + studentInfo.getStuenglishName() + "%%");
}
if (studentInfo.getStuapplyTimeStart() != null) {
hql += " and t.stuapplyTime >= :stuapplyTimeStart";
params.put("stuapplyTimeStart", studentInfo.getStuapplyTimeStart());
}
if (studentInfo.getStuapplyTimeEnd() != null) {
hql += " and t.stuapplyTime <= :stuapplyTimeEnd";
params.put("stuapplyTimeEnd", studentInfo.getStuapplyTimeEnd());
}
}
return hql;
} //-------------查询:已经签到的学生信息----------------------------- @Override
public List<TStudentinfo> dataGridIsReported(StudentInfo studentInfo, PageFilter ph) {
Map<String, Object> params = new HashMap<String, Object>();
String hql = " from TStudentinfo t ";
List<TStudentinfo> l = tstudentInfoDao.find(hql + whereHqlIsReported(studentInfo, params) + orderHqlIsReported(ph), params, ph.getPage(), ph.getRows()); return l;
} @Override
public Long countIsReported(StudentInfo studentInfo, PageFilter ph) {
Map<String, Object> params = new HashMap<String, Object>();
String hql = " from TStudentinfo t ";
return tstudentInfoDao.count("select count(*) " + hql + whereHqlToReport(studentInfo, params), params);
} /**
*
* @author 刘军
* @date 2016-4-16 下午11:17:07  * @version V1.0   * @Title: whereHql  * @Description: ( datagrid 拼接查询语句 )  * @param @param studentInfo
* @param @param params
* @param @return    设定文件  * @return String    返回类型  * @throws  */
private String whereHqlIsReported(StudentInfo studentInfo, Map<String, Object> params) {
String hql = "";
if (studentInfo != null) {
hql += " where 1=1 and t.stustatus=1 and t.stuid in"
+ " (select tr.stuid from TReportsorexit tr "
+ " WHERE tr.reportstime BETWEEN TIMESTAMP(DATE(SYSDATE())) AND TIMESTAMP(ADDDATE(DATE(SYSDATE()),1)) ) ";
if (studentInfo.getStuname() != null && !studentInfo.getStuname().equals("") ) {
hql += " and t.stuname like :stuname";
params.put("stuname", "%%" + studentInfo.getStuname() + "%%");
}
if (studentInfo.getStuenglishName() != null && !studentInfo.getStuenglishName().equals("") ) {
hql += " and t.stuenglishName like :stuenglishName";
params.put("stuenglishName", "%%" + studentInfo.getStuenglishName() + "%%");
}
if (studentInfo.getStuapplyTimeStart() != null) {
hql += " and t.stuapplyTime >= :stuapplyTimeStart";
params.put("stuapplyTimeStart", studentInfo.getStuapplyTimeStart());
}
if (studentInfo.getStuapplyTimeEnd() != null) {
hql += " and t.stuapplyTime <= :stuapplyTimeEnd";
params.put("stuapplyTimeEnd", studentInfo.getStuapplyTimeEnd());
}
}
return hql;
} /**
*
* @author 刘军
* @date 2016-4-16 下午11:18:25  * @version V1.0   * @Title: orderHql  * @Description: (datagrid 拼接 排序)  * @param @param ph
* @param @return    设定文件  * @return String    返回类型  * @throws  */
private String orderHqlIsReported(PageFilter ph) {
String orderString = "";
if ((ph.getSort() != null) && (ph.getOrder() != null)) {
orderString = " order by t." + ph.getSort() + "" + ph.getOrder();
}
return orderString;
} //------------------------------------------------------------------------- /**
* 添加学生信息
*/
@Override
public void add(StudentInfo studentInfo) {
TStudentinfo tStudentinfo = new TStudentinfo();
BeanUtils.copyProperties(studentInfo, tStudentinfo);
tStudentinfo.setStuapplyTime(new Date());//创建时间
tStudentinfo.setStustatus(1);//有效状态
tStudentinfo.setStudayCost( studentInfo.getStudayCost() );
tstudentInfoDao.save(tStudentinfo);
}
/**
*
* @author 刘军
* @date 2016-4-16 下午11:18:25  * @version V1.0   * @Title: orderHql  * @Description: ( 删除学生信息)  * @param @param ph
* @param @return    设定文件  * @return String    返回类型  * @throws  */
@Override
public void delete(Long id) {
TStudentinfo studentInfo = tstudentInfoDao.get(TStudentinfo.class, id);
studentInfo.setStustatus(0);//置为无效状态
//获取登陆 用户信息
SessionInfo sessionInfo=(SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO);
THisStudentinfo hisStudentinfo=new THisStudentinfo() ;
BeanUtils.copyProperties(studentInfo, hisStudentinfo);
//保存:修改用户信息的操作员信息
hisStudentinfo.setUpdateTime(new Date());
hisStudentinfo.setUpdateUserId(Integer.parseInt((sessionInfo.getId()+"").trim()));
hisStudentinfo.setActionMethod("delete");
//保存历史表信息
hisStudentInfoDao.save(hisStudentinfo); //跟新数据
tstudentInfoDao.update(studentInfo);
}
/**
*
* @author 刘军
* @date 2016-4-16 下午11:18:25  * @version V1.0   * @Title: orderHql  * @Description: ( 根据学生id 获取学生信息)  * @param @param ph
* @param @return    设定文件  * @return String    返回类型  * @throws  */
@Override
public TStudentinfo get(Long id) {
TStudentinfo studentInfo = tstudentInfoDao.get(TStudentinfo.class, id);
return studentInfo;
}
/**
*
* @author 刘军
* @date 2016-4-16 下午11:18:25  * @version V1.0   * @Title: orderHql  * @Description: ( 修改 学生信息 )  * @param @param ph
* @param @return    设定文件  * @return String    返回类型  * @throws  */
@Override
public void edit(TStudentinfo studentInfo) { //获取登陆 用户信息
SessionInfo sessionInfo=(SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO); THisStudentinfo hisStudentinfo=new THisStudentinfo() ;
TStudentinfo studentinfo2=queryfirst((long)studentInfo.getStuid()) ;//get((long)studentInfo.getUserid());
BeanUtils.copyProperties(studentinfo2, hisStudentinfo); //保存:修改用户信息的操作员信息
hisStudentinfo.setUpdateTime(new Date());
hisStudentinfo.setUpdateUserId(Integer.parseInt((sessionInfo.getId()+"").trim()));
hisStudentinfo.setActionMethod("update");
//保存历史表信息
hisStudentInfoDao.save(hisStudentinfo); //跟新数据
tstudentInfoDao.update(studentInfo);
}
/**
* 查询第一条数据
*/
public TStudentinfo queryfirst(Long stuid) {
String sql = "select * from t_studentinfo where stuid= ?";
Object[] obj = {stuid};
return (TStudentinfo) daoImpl.find(sql, obj, new TStudentInfoMapper()) ;
}
}

JavaBean 层:TStudentinfo.java

 package com.jacezhu.model.businessCore.CustomerManagement;

 import java.util.Date;

 import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table; /**
* TStudentinfo entity. @author MyEclipse Persistence Tools
* 学生信息注册管理
*/
@Entity
@Table(name = "t_studentinfo", catalog = "xlzj_sh")
public class TStudentinfo implements java.io.Serializable { // Fields private Long stuid;//学生信息表主键 id
private String stuname;//学生名字
private String stuenglishName;//学生英文名
private Integer stusex;//学生性别 dic: 0 ;男 1 女
private String stubrithday;//学生生日
private String stuschool;//学生就读于那个学校
private String stugrade;//学生是几年级的
private Integer studepartment;//中/英文部 dic: 1 中文部 2英文部
private String stuRegistration;//报名方式 dic: 0 :晚托班 1:1对1辅导 2:上门家教服务 3:其他
private Integer stupickUp;//是否接送 dic: 1 接送 ;0 :不接送
private String stuattention;//注意事项
private String stuhobby;//兴趣爱好
private String stuavoidFood;//忌口食物
private String stuallergySmptoms;//过敏症状
private String stuacuteillness;//急性病史
private String stuotherInfo;//其他信息
private Long prId;//家长信息表主键
private Integer stustatus;//学生有效状态 dic: 0 无效 1:有效
private Date stuapplyTime;//注册时间
private Integer userid;//注册人id
private String druguse;//drug use 药物使用
private String stuschoolTech;// 学生在学校的负责老师姓名
private String stuschoolTechTel;//学生在校的负责老师的联系电话
private String startStudayDate;//课程服务的起始时间
private String endStudayDate;//课程服务的终止时间
private String studayCost;//学费 // Constructors /** default constructor */
public TStudentinfo() {
} /** full constructor */
public TStudentinfo(String stuname, String stuenglishName, Integer stusex,
String stubrithday, String stuschool, String stugrade,
Integer studepartment, String stuRegistration, Integer stupickUp,
String stuattention, String stuhobby, String stuavoidFood,
String stuallergySmptoms, String stuacuteillness,
String stuotherInfo, Long prId, Integer stustatus,
Date stuapplyTime, Integer userid, String druguse ,String stuschoolTech, String stuschoolTechTel,
String startStudayDate , String endStudayDate , String studayCost) {
this.stuname = stuname;
this.stuenglishName = stuenglishName;
this.stusex = stusex;
this.stubrithday = stubrithday;
this.stuschool = stuschool;
this.stugrade = stugrade;
this.studepartment = studepartment;
this.stuRegistration = stuRegistration;
this.stupickUp = stupickUp;
this.stuattention = stuattention;
this.stuhobby = stuhobby;
this.stuavoidFood = stuavoidFood;
this.stuallergySmptoms = stuallergySmptoms;
this.stuacuteillness = stuacuteillness;
this.stuotherInfo = stuotherInfo;
this.prId = prId;
this.stustatus = stustatus;
this.stuapplyTime = stuapplyTime;
this.userid = userid;
this.druguse = druguse;
this.stuschoolTech = stuschoolTech;
this.stuschoolTechTel = stuschoolTechTel;
this.startStudayDate = startStudayDate;
this.endStudayDate = endStudayDate;
this.studayCost = studayCost;
} // Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "stuid", unique = true, nullable = false)
public Long getStuid() {
return this.stuid;
} public void setStuid(Long stuid) {
this.stuid = stuid;
} @Column(name = "stuname", length = 50)
public String getStuname() {
return this.stuname;
} public void setStuname(String stuname) {
this.stuname = stuname;
} @Column(name = "stuenglishName", length = 50)
public String getStuenglishName() {
return this.stuenglishName;
} public void setStuenglishName(String stuenglishName) {
this.stuenglishName = stuenglishName;
} @Column(name = "stusex", length = 1)
public Integer getStusex() {
return this.stusex;
} public void setStusex(Integer stusex) {
this.stusex = stusex;
} @Column(name = "stubrithday", length = 10)
public String getStubrithday() {
return this.stubrithday;
} public void setStubrithday(String stubrithday) {
this.stubrithday = stubrithday;
} @Column(name = "stuschool", length = 100)
public String getStuschool() {
return this.stuschool;
} public void setStuschool(String stuschool) {
this.stuschool = stuschool;
} @Column(name = "stugrade", length = 10)
public String getStugrade() {
return this.stugrade;
} public void setStugrade(String stugrade) {
this.stugrade = stugrade;
} @Column(name = "studepartment", length = 1)
public Integer getStudepartment() {
return this.studepartment;
} public void setStudepartment(Integer studepartment) {
this.studepartment = studepartment;
} @Column(name = "stuRegistration", length = 1)
public String getStuRegistration() {
return this.stuRegistration;
} public void setStuRegistration(String stuRegistration) {
this.stuRegistration = stuRegistration;
} @Column(name = "stupickUp", length = 1)
public Integer getStupickUp() {
return this.stupickUp;
} public void setStupickUp(Integer stupickUp) {
this.stupickUp = stupickUp;
} @Column(name = "stuattention", length = 500)
public String getStuattention() {
return this.stuattention;
} public void setStuattention(String stuattention) {
this.stuattention = stuattention;
} @Column(name = "stuhobby", length = 200)
public String getStuhobby() {
return this.stuhobby;
} public void setStuhobby(String stuhobby) {
this.stuhobby = stuhobby;
} @Column(name = "stuavoidFood", length = 200)
public String getStuavoidFood() {
return this.stuavoidFood;
} public void setStuavoidFood(String stuavoidFood) {
this.stuavoidFood = stuavoidFood;
} @Column(name = "stuallergySmptoms", length = 500)
public String getStuallergySmptoms() {
return this.stuallergySmptoms;
} public void setStuallergySmptoms(String stuallergySmptoms) {
this.stuallergySmptoms = stuallergySmptoms;
} @Column(name = "stuacuteillness", length = 500)
public String getStuacuteillness() {
return this.stuacuteillness;
} public void setStuacuteillness(String stuacuteillness) {
this.stuacuteillness = stuacuteillness;
} @Column(name = "stuotherInfo", length = 500)
public String getStuotherInfo() {
return this.stuotherInfo;
} public void setStuotherInfo(String stuotherInfo) {
this.stuotherInfo = stuotherInfo;
} @Column(name = "prId")
public Long getPrId() {
return this.prId;
} public void setPrId(Long prId) {
this.prId = prId;
} @Column(name = "stustatus", length = 1)
public Integer getStustatus() {
return this.stustatus;
} public void setStustatus(Integer stustatus) {
this.stustatus = stustatus;
} @Column(name = "stuapplyTime" )
public Date getStuapplyTime() {
return this.stuapplyTime;
} public void setStuapplyTime(Date stuapplyTime) {
this.stuapplyTime = stuapplyTime;
} @Column(name = "userid")
public Integer getUserid() {
return this.userid;
} public void setUserid(Integer userid) {
this.userid = userid;
} @Column(name = "druguse", length = 500)
public String getDruguse() {
return this.druguse;
} public void setDruguse(String druguse) {
this.druguse = druguse;
} @Column(name = "stuschool_tech", length = 100)
public String getStuschoolTech() {
return this.stuschoolTech;
} public void setStuschoolTech(String stuschoolTech) {
this.stuschoolTech = stuschoolTech;
} @Column(name = "stuschool_tech_tel", length = 20)
public String getStuschoolTechTel() {
return this.stuschoolTechTel;
} public void setStuschoolTechTel(String stuschoolTechTel) {
this.stuschoolTechTel = stuschoolTechTel;
} @Column(name = "start_studay_date", length = 19)
public String getStartStudayDate() {
return this.startStudayDate;
} public void setStartStudayDate(String startStudayDate) {
this.startStudayDate = startStudayDate;
} @Column(name = "end_studay_date", length = 19)
public String getEndStudayDate() {
return this.endStudayDate;
} public void setEndStudayDate(String endStudayDate) {
this.endStudayDate = endStudayDate;
} @Column(name = "studay_cost", precision = 16, scale = 0)
public String getStudayCost() {
return this.studayCost;
} public void setStudayCost(String studayCost) {
this.studayCost = studayCost;
}
}

JavaBean 参数对象:StudentInfo.java

 package com.jacezhu.model.businessCore.CustomerManagement.vo;
import java.util.Date;
/**
*
* @Title: StudentInfo.java  * @Package com.jacezhu.pageModel.businessCore.CustomerManagement  * @Description: (
* beanVo 用于接收查询条件 的参数
* )  * @author liujun<1136808529@qq.coom>
* @date 2016-4-24 下午12:11:17  * @version V1.0   */
public class StudentInfo implements java.io.Serializable { // Fields /**  * @Fields serialVersionUID : (用一句话描述这个变量表示什么)  */
private static final long serialVersionUID = 1L;
private Long stuid;//学生信息表主键 id
private String stuname;//学生名字
private String stuenglishName;//学生英文名
private Integer stusex;//学生性别 dic: 0 ;男 1 女
private String stubrithday;//学生生日
private String stuschool;//学生就读于那个学校
private String stugrade;//学生是几年级的
private Integer studepartment;//中/英文部 dic: 1 中文部 2英文部
private String stuRegistration;//报名方式 dic: 0 :晚托班 1:1对1辅导 2:上门家教服务 3:其他
private Integer stupickUp;//是否接送 dic: 1 接送 ;0 :不接送
private String stuattention;//注意事项
private String stuhobby;//兴趣爱好
private String stuavoidFood;//忌口食物
private String stuallergySmptoms;//过敏症状
private String stuacuteillness;//急性病史
private String stuotherInfo;//其他信息
private Long prId;//家长信息表主键
private Integer stustatus;//学生有效状态 dic: 0 无效 1:有效
private String stuapplyTime;//注册时间
private Integer userid;//注册人id
private String druguse;//drug use 药物使用
private Date stuapplyTimeStart;
private Date stuapplyTimeEnd;
private String stuschoolTech;// 学生在学校的负责老师姓名
private String stuschoolTechTel;//学生在校的负责老师的联系电话
private String startStudayDate;//课程服务的起始时间
private String endStudayDate;//课程服务的终止时间
private String studayCost;//学费 public Date getStuapplyTimeStart() {
return stuapplyTimeStart;
}
public void setStuapplyTimeStart(Date stuapplyTimeStart) {
this.stuapplyTimeStart = stuapplyTimeStart;
}
public Date getStuapplyTimeEnd() {
return stuapplyTimeEnd;
}
public void setStuapplyTimeEnd(Date stuapplyTimeEnd) {
this.stuapplyTimeEnd = stuapplyTimeEnd;
}
public Long getStuid() {
return stuid;
}
public void setStuid(Long stuid) {
this.stuid = stuid;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public String getStuenglishName() {
return stuenglishName;
}
public void setStuenglishName(String stuenglishName) {
this.stuenglishName = stuenglishName;
}
public Integer getStusex() {
return stusex;
}
public void setStusex(Integer stusex) {
this.stusex = stusex;
}
public String getStubrithday() {
return stubrithday;
}
public void setStubrithday(String stubrithday) {
this.stubrithday = stubrithday;
}
public String getStuschool() {
return stuschool;
}
public void setStuschool(String stuschool) {
this.stuschool = stuschool;
}
public String getStugrade() {
return stugrade;
}
public void setStugrade(String stugrade) {
this.stugrade = stugrade;
}
public Integer getStudepartment() {
return studepartment;
}
public void setStudepartment(Integer studepartment) {
this.studepartment = studepartment;
}
public String getStuRegistration() {
return stuRegistration;
}
public void setStuRegistration(String stuRegistration) {
this.stuRegistration = stuRegistration;
}
public Integer getStupickUp() {
return stupickUp;
}
public void setStupickUp(Integer stupickUp) {
this.stupickUp = stupickUp;
}
public String getStuattention() {
return stuattention;
}
public void setStuattention(String stuattention) {
this.stuattention = stuattention;
}
public String getStuhobby() {
return stuhobby;
}
public void setStuhobby(String stuhobby) {
this.stuhobby = stuhobby;
}
public String getStuavoidFood() {
return stuavoidFood;
}
public void setStuavoidFood(String stuavoidFood) {
this.stuavoidFood = stuavoidFood;
}
public String getStuallergySmptoms() {
return stuallergySmptoms;
}
public void setStuallergySmptoms(String stuallergySmptoms) {
this.stuallergySmptoms = stuallergySmptoms;
}
public String getStuacuteillness() {
return stuacuteillness;
}
public void setStuacuteillness(String stuacuteillness) {
this.stuacuteillness = stuacuteillness;
}
public String getStuotherInfo() {
return stuotherInfo;
}
public void setStuotherInfo(String stuotherInfo) {
this.stuotherInfo = stuotherInfo;
}
public Long getPrId() {
return prId;
}
public void setPrId(Long prId) {
this.prId = prId;
}
public Integer getStustatus() {
return stustatus;
}
public void setStustatus(Integer stustatus) {
this.stustatus = stustatus;
}
public String getStuapplyTime() {
return stuapplyTime;
}
public void setStuapplyTime(String stuapplyTime) {
this.stuapplyTime = stuapplyTime;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getDruguse() {
return druguse;
}
public void setDruguse(String druguse) {
this.druguse = druguse;
}
public String getStuschoolTech() {
return stuschoolTech;
}
public void setStuschoolTech(String stuschoolTech) {
this.stuschoolTech = stuschoolTech;
}
public String getStuschoolTechTel() {
return stuschoolTechTel;
}
public void setStuschoolTechTel(String stuschoolTechTel) {
this.stuschoolTechTel = stuschoolTechTel;
}
public String getStartStudayDate() {
return startStudayDate;
}
public void setStartStudayDate(String startStudayDate) {
this.startStudayDate = startStudayDate;
}
public String getEndStudayDate() {
return endStudayDate;
}
public void setEndStudayDate(String endStudayDate) {
this.endStudayDate = endStudayDate;
}
public String getStudayCost() {
return studayCost;
}
public void setStudayCost(String studayCost) {
this.studayCost = studayCost;
} }

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


 package com.jacezhu.model.businessCore.CustomerManagement.mapper;

 import java.sql.ResultSet;

 import com.jacezhu.framework.connectUtil.jdbcUtl.ObjectMapper;
import com.jacezhu.model.businessCore.CustomerManagement.TStudentinfo; //
public class TStudentInfoMapper implements ObjectMapper { @Override
public Object mapping(ResultSet rs) {
TStudentinfo d=new TStudentinfo();
try{ d.setStuid(rs.getLong("stuid"));//学生信息表主键 id
d.setStuname(rs.getString("stuname"));//学生名字
d.setStuenglishName( rs.getString("stuenglishName") );//学生英文名
d.setStusex( rs.getInt("stusex") ); //学生性别 dic: 0 ;男 1 女
d.setStubrithday(rs.getString("stubrithday")); //学生生日
d.setStuschool(rs.getString("stuschool")); //学生就读于那个学校
d.setStugrade(rs.getString("stugrade")); //学生是几年级的
d.setStudepartment(rs.getInt("studepartment"));//中/英文部 dic: 1 中文部 2英文部
d.setStuRegistration(rs.getString("stuRegistration")); //报名方式 dic: 0 :晚托班 1:1对1辅导 2:上门家教服务 3:其他
d.setStupickUp(rs.getInt("stupickUp")); //是否接送 dic: 1 接送 ;0 :不接送
d.setStuattention(rs.getString("stuattention")); //注意事项
d.setStuhobby(rs.getString("stuhobby")); //兴趣爱好
d.setStuavoidFood(rs.getString("stuavoidFood"));//忌口食物
d.setStuallergySmptoms(rs.getString("stuallergySmptoms")); //过敏症状
d.setStuacuteillness(rs.getString("stuacuteillness")); //急性病史
d.setStuotherInfo(rs.getString("stuotherInfo")); //其他信息
d.setPrId(rs.getLong("prId"));//家长信息表主键
d.setStustatus(rs.getInt("stustatus"));//学生有效状态 dic: 0 无效 1:有效
d.setStuapplyTime(rs.getDate("stuapplyTime")); //注册时间
d.setUserid(rs.getInt("userId")); //注册人id
d.setDruguse(rs.getString("druguse")); //drug use 药物使用
d.setStuschoolTech(rs.getString("stuschool_tech"));//学生老师
d.setStuschoolTechTel(rs.getString("stuschool_tech_tel"));//学生老师电话
d.setStartStudayDate(rs.getString("start_studay_date"));//课程开始时间
d.setEndStudayDate(rs.getString("end_studay_date"));//课程结束时间
d.setStudayCost(rs.getString("studay_cost"));
}catch(Exception ex){
ex.printStackTrace();
}
return d;
} }

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

Config类

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

 package com.tly.dbutil;

 import java.io.IOException;
import java.util.Properties; public class Config {
private static Properties prop = new Properties();
static{
try {
//加载dbconfig.properties配置文件
prop.load(Config.class.getResourceAsStream("dbconfig.properties"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //设置常量
public static final String CLASS_NAME = prop.getProperty("CLASS_NAME");
public static final String DATABASE_URL = prop.getProperty("DATABASE_URL");
public static final String SERVER_IP = prop.getProperty("SERVER_IP");
public static final String SERVER_PORT = prop.getProperty("SERVER_PORT");
public static final String DATABASE_SID = prop.getProperty("DATABASE_SID");
public static final String USERNAME = prop.getProperty("USERNAME");
public static final String PASSWORD = prop.getProperty("PASSWORD"); }

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

 CLASS_NAME=com.mysql.jdbc.Driver
DATABASE_URL=jdbc:mysql
SERVER_IP=localhost
SERVER_PORT=3306
DATABASE_SID=employees
USERNAME=root
PASSWORD=1

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

 package com.employees.dbutil;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class DBConn {
//三属性、四方法 //三大核心接口
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null; //四个方法
//method1: 创建数据库的连接
public Connection getConntion(){
try {
//1: 加载连接驱动,Java反射原理
Class.forName(Config.CLASS_NAME);
//2:创建Connection接口对象,用于获取MySQL数据库的连接对象。三个参数:url连接字符串 账号 密码
String url = Config.DATABASE_URL+"://"+Config.SERVER_IP+":"+Config.SERVER_PORT+"/"+Config.DATABASE_SID;
conn = DriverManager.getConnection(url,Config.USERNAME,Config.PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
} //method2:关闭数据库的方法
public void closeConn(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} //method3: 专门用于发送增删改语句的方法
public int execOther(PreparedStatement pstmt){
try {
//1、使用Statement对象发送SQL语句
int affectedRows = pstmt.executeUpdate();
//2、返回结果
return affectedRows;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
} //method4: 专门用于发送查询语句
public ResultSet execQuery(PreparedStatement pstmt){
try {
//1、使用Statement对象发送SQL语句
rs = pstmt.executeQuery();
//2、返回结果
return rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
} }

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

BaseDao类

 package com.employees.dao;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import com.employees.dbutil.DBConn; public class BaseDAO<T> { DBConn conn = new DBConn();
private Connection connection = null; @SuppressWarnings("unused")
private Class<T> persistentClass; @SuppressWarnings("unchecked")
public BaseDAO() {
initConnection();
//获得参数化类型
ParameterizedType type = (ParameterizedType)getClass().getGenericSuperclass();
persistentClass = (Class<T>)type.getActualTypeArguments()[0];
} /**
* 获得数据库连接
*/
public void initConnection() {
connection = conn.getConntion();
} /**
* 保存
*/
public void save(T entity) throws Exception{
//SQL语句,insert into table name (
String sql = "insert into " + entity.getClass().getSimpleName().toLowerCase() + "("; //获得带有字符串get的所有方法的对象
List<Method> list = this.matchPojoMethods(entity,"get"); Iterator<Method> iter = list.iterator(); //拼接字段顺序 insert into table name(id,name,email,
while(iter.hasNext()) {
Method method = iter.next();
sql += method.getName().substring(3).toLowerCase() + ",";
} //去掉最后一个,符号insert insert into table name(id,name,email) values(
sql = sql.substring(0, sql.lastIndexOf(",")) + ") values("; //拼装预编译SQL语句insert insert into table name(id,name,email) values(?,?,?,
for(int j = 0; j < list.size(); j++) {
sql += "?,";
} //去掉SQL语句最后一个,符号insert insert into table name(id,name,email) values(?,?,?);
sql = sql.substring(0, sql.lastIndexOf(",")) + ")"; //到此SQL语句拼接完成,打印SQL语句
System.out.println(sql); //获得预编译对象的引用
PreparedStatement statement = connection.prepareStatement(sql); int i = 0;
//把指向迭代器最后一行的指针移到第一行.
iter = list.iterator();
while(iter.hasNext()) {
Method method = iter.next();
//此初判断返回值的类型,因为存入数据库时有的字段值格式需要改变,比如String,SQL语句是'"+abc+"'
if(method.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(method, entity));
} else if(method.getReturnType().getSimpleName().indexOf("Date") != -1){
statement.setDate(++i, this.getDate(method, entity));
} else if(method.getReturnType().getSimpleName().indexOf("InputStream") != -1) {
statement.setAsciiStream(++i, this.getBlob(method, entity),1440);
} else {
statement.setInt(++i, this.getInt(method, entity));
}
}
//执行
conn.execOther(statement);
//关闭连接
conn.closeConn();
} /**
* 修改
*/
public void update(T entity) throws Exception{
String sql = "update " + entity.getClass().getSimpleName().toLowerCase() + " set "; //获得该类所有get方法对象集合
List<Method> list = this.matchPojoMethods(entity,"get"); //临时Method对象,负责迭代时装method对象.
Method tempMethod = null; //由于修改时不需要修改ID,所以按顺序加参数则应该把Id移到最后.
Method idMethod = null;
Iterator<Method> iter = list.iterator();
while(iter.hasNext()) {
tempMethod = iter.next();
//如果方法名中带有ID字符串并且长度为2,则视为ID.
if(tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
//把ID字段的对象存放到一个变量中,然后在集合中删掉.
idMethod = tempMethod;
iter.remove();
//如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为ID
} else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
idMethod = tempMethod;
iter.remove();
}
} //把迭代指针移到第一位
iter = list.iterator();
while(iter.hasNext()) {
tempMethod = iter.next();
sql += tempMethod.getName().substring(3).toLowerCase() + "= ?,";
} //去掉最后一个,符号
sql = sql.substring(0,sql.lastIndexOf(",")); //添加条件
sql += " where " + idMethod.getName().substring(3).toLowerCase() + " = ?"; //SQL拼接完成,打印SQL语句
System.out.println(sql); PreparedStatement statement = this.connection.prepareStatement(sql); int i = 0;
iter = list.iterator();
while(iter.hasNext()) {
Method method = iter.next();
//此初判断返回值的类型,因为存入数据库时有的字段值格式需要改变,比如String,SQL语句是'"+abc+"'
if(method.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(method, entity));
} else if(method.getReturnType().getSimpleName().indexOf("Date") != -1){
statement.setDate(++i, this.getDate(method, entity));
} else if(method.getReturnType().getSimpleName().indexOf("InputStream") != -1) {
statement.setAsciiStream(++i, this.getBlob(method, entity),1440);
} else {
statement.setInt(++i, this.getInt(method, entity));
}
} //为Id字段添加值
if(idMethod.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(idMethod, entity));
} else {
statement.setInt(++i, this.getInt(idMethod, entity));
} //执行SQL语句
statement.executeUpdate(); //关闭预编译对象
statement.close(); //关闭连接
connection.close();
} /**
* 删除
*/
public void delete(T entity) throws Exception{
String sql = "delete from " + entity.getClass().getSimpleName().toLowerCase() + " where "; //存放字符串为"id"的字段对象
Method idMethod = null; //取得字符串为"id"的字段对象
List<Method> list = this.matchPojoMethods(entity, "get");
Iterator<Method> iter = list.iterator();
while(iter.hasNext()) {
Method tempMethod = iter.next();
//如果方法名中带有ID字符串并且长度为2,则视为ID.
if(tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
//把ID字段的对象存放到一个变量中,然后在集合中删掉.
idMethod = tempMethod;
iter.remove();
//如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为ID
} else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
idMethod = tempMethod;
iter.remove();
}
} sql += idMethod.getName().substring(3).toLowerCase() + " = ?"; PreparedStatement statement = this.connection.prepareStatement(sql); //为Id字段添加值
int i = 0;
if(idMethod.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(idMethod, entity));
} else {
statement.setInt(++i, this.getInt(idMethod, entity));
} //执行
conn.execOther(statement);
//关闭连接
conn.closeConn();
} /**
* 通过ID查询
*/
public T findById(Object object) throws Exception{
String sql = "select * from " + persistentClass.getSimpleName().toLowerCase() + " where "; //通过子类的构造函数,获得参数化类型的具体类型.比如BaseDAO<T>也就是获得T的具体类型
T entity = persistentClass.newInstance(); //存放Pojo(或被操作表)主键的方法对象
Method idMethod = null; List<Method> list = this.matchPojoMethods(entity, "set");
Iterator<Method> iter = list.iterator(); //过滤取得Method对象
while(iter.hasNext()) {
Method tempMethod = iter.next();
if(tempMethod.getName().indexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
idMethod = tempMethod;
} else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))){
idMethod = tempMethod;
}
}
//第一个字母转为小写
sql += idMethod.getName().substring(3,4).toLowerCase()+idMethod.getName().substring(4) + " = ?"; //封装语句完毕,打印sql语句
System.out.println(sql); //获得连接
PreparedStatement statement = this.connection.prepareStatement(sql); //判断id的类型
if(object instanceof Integer) {
statement.setInt(1, (Integer)object);
} else if(object instanceof String){
statement.setString(1, (String)object);
} //执行sql,取得查询结果集.
ResultSet rs = conn.execQuery(statement); //记数器,记录循环到第几个字段
int i = 0; //把指针指向迭代器第一行
iter = list.iterator(); //封装
while(rs.next()) {
while(iter.hasNext()) {
Method method = iter.next();
if(method.getParameterTypes()[0].getSimpleName().indexOf("String") != -1) {
//由于list集合中,method对象取出的方法顺序与数据库字段顺序不一致(比如:list的第一个方法是setDate,而数据库按顺序取的是"123"值)
//所以数据库字段采用名字对应的方式取.
this.setString(method, entity, rs.getString(method.getName().substring(3).toLowerCase()));
} else if(method.getParameterTypes()[0].getSimpleName().indexOf("Date") != -1){
this.setDate(method, entity, rs.getDate(method.getName().substring(3).toLowerCase()));
} else if(method.getParameterTypes()[0].getSimpleName().indexOf("InputStream") != -1) {
this.setBlob(method, entity, rs.getBlob(method.getName().substring(3).toLowerCase()).getBinaryStream());
} else {
this.setInt(method, entity, rs.getInt(method.getName().substring(3).toLowerCase()));
}
}
} //关闭结果集
rs.close(); //关闭预编译对象
statement.close(); return entity;
} /**
* 过滤当前Pojo类所有带传入字符串的Method对象,返回List集合.
*/
private List<Method> matchPojoMethods(T entity,String methodName) {
//获得当前Pojo所有方法对象
Method[] methods = entity.getClass().getDeclaredMethods(); //List容器存放所有带get字符串的Method对象
List<Method> list = new ArrayList<Method>(); //过滤当前Pojo类所有带get字符串的Method对象,存入List容器
for(int index = 0; index < methods.length; index++) {
if(methods[index].getName().indexOf(methodName) != -1) {
list.add(methods[index]);
}
}
return list;
} /**
* 方法返回类型为int或Integer类型时,返回的SQL语句值.对应get
*/
public Integer getInt(Method method, T entity) throws Exception{
return (Integer)method.invoke(entity, new Object[]{});
} /**
* 方法返回类型为String时,返回的SQL语句拼装值.比如'abc',对应get
*/
public String getString(Method method, T entity) throws Exception{
return (String)method.invoke(entity, new Object[]{});
} /**
* 方法返回类型为Blob时,返回的SQL语句拼装值.对应get
*/
public InputStream getBlob(Method method, T entity) throws Exception{
return (InputStream)method.invoke(entity, new Object[]{});
} /**
* 方法返回类型为Date时,返回的SQL语句拼装值,对应get
*/
public Date getDate(Method method, T entity) throws Exception{
return (Date)method.invoke(entity, new Object[]{});
} /**
* 参数类型为Integer或int时,为entity字段设置参数,对应set
*/
public Integer setInt(Method method, T entity, Integer arg) throws Exception{
return (Integer)method.invoke(entity, new Object[]{arg});
} /**
* 参数类型为String时,为entity字段设置参数,对应set
*/
public String setString(Method method, T entity, String arg) throws Exception{
return (String)method.invoke(entity, new Object[]{arg});
} /**
* 参数类型为InputStream时,为entity字段设置参数,对应set
*/
public InputStream setBlob(Method method, T entity, InputStream arg) throws Exception{
return (InputStream)method.invoke(entity, new Object[]{arg});
} /**
* 参数类型为Date时,为entity字段设置参数,对应set
*/
public Date setDate(Method method, T entity, Date arg) throws Exception{
return (Date)method.invoke(entity, new Object[]{arg});
}
}

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

 package com.employees.dao;

 import java.util.ArrayList;
import java.util.List;
import com.employees.po.Employees; public class EmployeesDao extends BaseDAO<Employees> { // 添加员工信息的操作
public boolean addEmployees(final Employees employees) throws Exception {
save(employees);
return true;
} // 将员工信息添加到表格中
public List<Employees> addEmployees(int id) throws Exception {
List<Employees> lstEmployees = new ArrayList<Employees>();
Employees employees = findById(id);
// 将当前封转好的数据装入对象中
lstEmployees.add(employees);
return lstEmployees;
} public void deleteEmp(final Employees entity) throws Exception {
this.delete(entity);
} public void updateEmp(final Employees entity) throws Exception {
this.update(entity);
} }

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

 package com.employees.dao;

 import org.junit.Test;

 import com.employees.po.Employees;

 public class EmployeesDaoTest {

     @Test
public void testAdd() throws Exception {
Employees emp = new Employees();
emp.setPname("tly");
emp.setPsex("男");
emp.setPbeliefs("xxxxx");
emp.setPaddr("天河");
emp.setPhobby("打篮球");
emp.setPsubject("计算机");
emp.setPtel("");
EmployeesDao dao = new EmployeesDao();
dao.addEmployees(emp);
}
@Test
public void testUpdate() throws Exception {
EmployeesDao dao = new EmployeesDao();
Employees emp = dao.findById(14);
emp.setPtel("");
dao.updateEmp(emp);
}
@Test
public void testdelete() throws Exception {
EmployeesDao dao = new EmployeesDao();
Employees emp = dao.findById(15);
dao.deleteEmp(emp);
} }

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