当前位置:网站首页>A common Dao class and util
A common Dao class and util
2022-07-24 14:21:00 【yn00】
import java.io.Serializable;
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.Iterator;
import java.util.List;
import java.util.Map;
import javax.sql.rowset.CachedRowSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.kmi.util.Util;
import com.sun.rowset.CachedRowSetImpl;
public class JdbcDaoSupport<T extends Serializable> {
private final Log log = LogFactory.getLog(this.getClass());
public int save(Connection conn, String sql, List<Object> mList) {
getValidConnection(conn);
int autoId = -1;
if (conn == null) {
return autoId;
}
PreparedStatement psment = null;
ResultSet rsment = null;
try {
log.debug("JdbcDaoSupport.Save sql = " + sql);
psment = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
setParameters(psment, mList);
int count = psment.executeUpdate();
if (count >= 0) {
rsment = psment.getGeneratedKeys();
while (rsment.next()) {
autoId = rsment.getInt(1);
}
}
} catch (Exception e) {
e.printStackTrace();
autoId = -1;
} finally {
DBManager.closePreparedStatement(psment);
}
return autoId;
}
/**
* perform Save perhaps Update operation
*
* @param conn
* Database connection
* @param sql
* Save perhaps Update SQL
* @param mList
* Parameters List
* @return
*/
public boolean saveOrUpdate(Connection conn, String sql, List<Object> mList) {
getValidConnection(conn);
boolean executeState = false;
PreparedStatement psment = null;
try {
psment = conn.prepareStatement(sql);
log.debug("JdbcDaoSupport.saveOrUpdate sql = " + sql);
setParameters(psment, mList);
int count = psment.executeUpdate();
if (count >= 0) {
executeState = true;
}
} catch (Exception e) {
e.printStackTrace();
executeState = false;
} finally {
DBManager.closePreparedStatement(psment);
}
return executeState;
}
/**
* Calling stored procedure
*
* @param conn
* @param procName
* @param list
* @return
*/
public List<Object[]> callProc(Connection conn, String procName, List<Object> list) {
if (Util.isStringEmpty(procName)) {
return null;
}
getValidConnection(conn);
CallableStatement callStatement = null;
ResultSet rsment = null;
ResultSetMetaData rsmd = null;
List<Object[]> objList = new ArrayList<Object[]>();
try {
log.debug("JdbcDaoSupport.callProc procName = " + procName);
callStatement = conn.prepareCall(procName);
if (!Util.isCollectionEmpty(list)) {
for (int i = 0; i < list.size(); i++) {
callStatement.setString(i + 1, list.get(i).toString());
}
}
rsment = callStatement.executeQuery();
rsmd = rsment.getMetaData();
int cols = rsmd.getColumnCount();
if (cols > 0) {
while (rsment.next()) {
Object[] obj = new Object[cols];
for (int i = 0; i < obj.length; i++) {
obj[i] = rsment.getObject(i + 1);
}
objList.add(obj);
}
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBManager.closeResultSet(rsment);
DBManager.closeCallableStatement(callStatement);
}
return objList;
}
/**
* Inquire about ( return List<Map<name,value>>)
*
* @param conn
* @param sql
* @param list
* @return
*/
public List<Map<String, Object>> queryForMap(Connection conn, String sql, List<Object> list) {
if (Util.isStringEmpty(sql)) {
return null;
}
getValidConnection(conn);
PreparedStatement psment = null;
ResultSet rsment = null;
ResultSetMetaData rsmd = null;
List<Map<String, Object>> objList = new ArrayList<Map<String, Object>>();
Map<String, Object> map = null;
try {
log.debug("JdbcDaoSupport.queryForMap sql = " + sql);
psment = conn.prepareStatement(sql);
setParameters(psment, list);
rsment = psment.executeQuery();
rsmd = rsment.getMetaData();
int cols = rsmd.getColumnCount();
while (rsment.next()) {
map = new HashMap<String, Object>();
for (int i = 0; i < cols; i++) {
map.put(rsmd.getColumnName(i + 1), rsment.getObject(i + 1));
}
objList.add(map);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBManager.closeResultSet(rsment);
DBManager.closePreparedStatement(psment);
}
return objList;
}
private void setParameters(PreparedStatement psment, List<Object> mList) throws SQLException {
if (Util.isCollectionEmpty(mList)) {
return;
}
for (int i = 0; i < mList.size(); i++) {
psment.setObject(i + 1, mList.get(i));
}
}
private List<?> getEntity(List<Map<String, Object>> entityList, Class<?> clazz) {
List<Object> mList = new ArrayList<Object>();
try {
String key = null;
Object obj = null;
Object tempVale = null;
Field[] fa = clazz.getDeclaredFields();
for (Map<String, Object> map : entityList) {
obj = (Object) Class.forName(clazz.getName()).newInstance();
for (Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
key = entry.getKey();
tempVale = entry.getValue();
if (tempVale == null) {
continue;
}
for (Field field : fa) {
if (field.getName().equalsIgnoreCase(key)) {
field.setAccessible(true);
field.set(obj, entry.getValue());
}
}
}
mList.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return mList;
}
/**
* Perform batch add
*
* @param conn
* @param sql
* @param paramList
* @return
*/
public boolean batchExecRecord(Connection conn, String sql, List<List<Object>> paramList) {
boolean status = false;
PreparedStatement psment = null;
try {
getValidConnection(conn);
psment = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
for (int i = 0; i < paramList.size(); i++) {
List<Object> param = paramList.get(i);
for (int j = 0; j < param.size(); j++) {
psment.setObject(j + 1, param.get(j));
}
psment.addBatch();
}
int[] b = psment.executeBatch();
if (b != null && b.length > 0) {
status = true;
}
} catch (Exception e) {
status = false;
e.printStackTrace();
}
return status;
}
/**
* Execute the query SQL
*
* @param conn
* @param sql
* @param mList
* @return
*/
public CachedRowSet executeQuerySQL(Connection conn, String sql, List<Object> list) {
// TODO Auto-generated method stub
if (Util.isStringEmpty(sql)) {
return null;
}
PreparedStatement psment = null;
ResultSet rsment = null;
CachedRowSet crs = null;
try {
log.debug("JdbcDaoSupport.Method executeQuerySQL = " + sql);
psment = conn.prepareStatement(sql);
setParameters(psment, list);
rsment = psment.executeQuery();
crs = new CachedRowSetImpl();
crs.populate(rsment);
} catch (Exception e) {
e.printStackTrace();
} finally {
DBManager.closeResultSet(rsment);
DBManager.closePreparedStatement(psment);
}
return crs;
}
public void getValidConnection(Connection conn) {
try {
if (conn == null || conn.isClosed()) {
conn = DBManager.getConnection();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Clear table data
*
* @param conn
* Database connection
* @param tableName
* Name of table
* @return
*/
public boolean emptyTableData(Connection conn, String tableName) {
boolean status = false;
if (Util.isStringEmpty(tableName)) {
return status;
}
PreparedStatement psment = null;
System.out.println("TRUNCATE table :" + tableName);
StringBuffer buff = new StringBuffer("TRUNCATE TABLE ");
buff.append(tableName);
try {
psment = conn.prepareStatement(buff.toString());
psment.executeUpdate();
status = true;
} catch (SQLException e) {
status = false;
e.printStackTrace();
} finally {
DBManager.closePreparedStatement(psment);
}
return status;
}
}DBManager
import java.io.IOException;
import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBManager {
private static final String DB_LOCATION = "dbcpconfig.properties";
private static BasicDataSource dataSource = null;
public DBManager() {
}
public static void init() {
if (dataSource != null) {
try {
dataSource.close();
} catch (Exception e) {
e.printStackTrace();
}
dataSource = null;
}
try {
Properties properties = new Properties();
InputStream input = null;
try {
input = DBManager.class.getClassLoader().getResourceAsStream(DB_LOCATION);
properties.load(input);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(getConnection());
}
public static synchronized Connection getConnection() {
Connection conn = null;
try {
if (dataSource == null) {
init();
}
if (dataSource != null) {
conn = dataSource.getConnection();
}
conn.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public synchronized static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public synchronized static void closeResultSet(ResultSet rsment) {
if (rsment != null) {
try {
rsment.close();
rsment = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public synchronized static void closeCachedRowSet(CachedRowSet rs) {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public synchronized static void closeStatement(Statement stment) {
if (stment != null) {
try {
stment.close();
stment = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public synchronized static void closeCallableStatement(CallableStatement call) {
if (call != null) {
try {
call.close();
call = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public synchronized static void closePreparedStatement(PreparedStatement psment) {
if (psment != null) {
try {
psment.close();
psment = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static DataSource ds;
}Util
package com.kmi.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
public class Util {
/**
* Determines if the string is empty
* @param str
* @return
*/
public static boolean isStringEmpty(String str) {
return str == null || str.length() == 0;
}
/**
* Determines if the set is empty
* @param collection
* @return
*/
public static boolean isCollectionEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
/**
* Determine whether the array is empty
* @param obj
* @return
*/
public static boolean isArrayEmpty(Object[] obj) {
return obj == null || obj.length == 0;
}
/**
* file save
*
* @param file
* File to save
* @param path
* Saved file path
* @param fileName
* File name
* @return boolean
*/
public static boolean saveFile(File file, String path, String fileName) {
boolean b = false;
try {
// String root = ServletActionContext.getRequest().getRealPath("/") + path;
// String root = PropertiesUtils.getProperties("asm_file_path")+path;
String root = path;
File f = new File(root);
if (!f.isDirectory()) {
f.mkdirs();
}
InputStream is = new FileInputStream(file);
File destFile = new File(root, fileName);
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[1025];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
b = true;
} catch (Exception e) {
b = false;
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
}
边栏推荐
- 电赛设计报告模板及
- [oauth2] III. interpretation of oauth2 configuration
- Complete set of JS array common operations
- Atcoder beginer contest 261 f / / tree array
- Mmdrawercontroller first loading sidebar height problem
- Video game design report template and resources over the years
- “00后”来了!数睿数据迎来新生代「无代码」生力军
- Centos7安装达梦单机数据库
- sql server语法—创建数据库
- 自动化渗透扫描工具
猜你喜欢

Not configured in app.json (uni releases wechat applet)

正则表达和绕过案例
![Rasa 3.x 学习系列-Rasa [3.2.4] - 2022-07-21 新版本发布](/img/1e/27f107d514ded6641410cc5a45764b.png)
Rasa 3.x 学习系列-Rasa [3.2.4] - 2022-07-21 新版本发布

达梦实时主备集群搭建

Number of bytes occupied by variables of type char short int in memory

Unity pedestrians walk randomly without collision

IEEE Transaction期刊模板使用注意事项

Mini examination - examination system

After five years of contact with nearly 100 bosses, as a headhunter, I found that the secret of promotion was only four words

Multithreaded common classes
随机推荐
SQL Server syntax - create database
The difference and relation among list, set and map
Fraud detection cases and Titanic rescued cases
JS get object attribute value
Mini examination - examination system
正则表达和绕过案例
【机器学习】之 主成分分析PCA
2022 IAA industry category development insight series report - phase II
AtCoder Beginner Contest 261 F // 树状数组
Activate the newly installed Anaconda in the server
北京一卡通以35288.8529万元挂牌出让68.45%股权,溢价率为84%
The fourth edition of Zhejiang University probability proves that the uncorrelation of normal distribution random variables is equivalent to independence
Source code analysis of ArrayList
2.4. properties of special profile
Multithreaded common classes
Su Chunyuan, founder of science and technology · CEO of Guanyuan data: making business use is the key to the Bi industry to push down the wall of penetration
Simple understanding and implementation of unity delegate
Ztree tree Metro style mouse through the display user-defined controls add, edit, delete, down, up operations
字符串——剑指 Offer 58 - II. 左旋转字符串
Remove the treasure box app with the green logo that cannot be deleted from iPhone