当前位置:网站首页>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;
}
}
边栏推荐
- threw exception [Circular view path [index]: would dispatch back to the current handler URL [/index]
- Automated penetration scanning tool
- 小熊派 课程导读
- The fourth edition of Zhejiang University probability proves that the uncorrelation of normal distribution random variables is equivalent to independence
- [NLP] next stop, embossed AI
- Moving the mouse into select options will trigger the mouseleave event processing scheme
- Data Lake series articles
- C# 多线程锁整理记录
- 2022.7.22 simulation match
- Solve the problem that the ARR containsobject method returns no every time
猜你喜欢

Detailed explanation of address bus, data bus and control bus

5年接触近百位老板,身为猎头的我,发现升职的秘密不过4个字

对话框管理器第二章:创建框架窗口

2022.7.22 simulation match

Unity pedestrians walk randomly without collision

Concurrent programming ----------- set

OWASP zap security testing tool tutorial (Advanced)

Nessus security testing tool tutorial

Moving the mouse into select options will trigger the mouseleave event processing scheme

Maotai ice cream "bucked the trend" and became popular, but its cross-border meaning was not "selling ice cream"
随机推荐
SQL subquery
电赛设计报告模板及历年资源
【NLP】下一站,Embodied AI
“00后”来了!数睿数据迎来新生代「无代码」生力军
Detailed explanation of address bus, data bus and control bus
ISPRS2018/云检测:Cloud/shadow detection based on spectral indices for multi/hyp基于光谱指数的多/高光谱光学遥感成像仪云/影检测
Mmdrawercontroller first loading sidebar height problem
Csp2021 T1 corridor bridge distribution
Nmap security testing tool tutorial
Not configured in app.json (uni releases wechat applet)
CSDN garbage has no bottom line!
JS judge whether the data is empty
The difference and relation among list, set and map
C multithreaded lock collation record
北京一卡通以35288.8529万元挂牌出让68.45%股权,溢价率为84%
Data Lake series articles
Maotai ice cream "bucked the trend" and became popular, but its cross-border meaning was not "selling ice cream"
String -- 28. Implement strstr()
Beijing all in one card listed and sold 68.45% of its equity at 352.888529 million yuan, with a premium rate of 84%
Stack and queue - 225. Implement stack with queue