public class DBUtils {
@Value("${spring.account.driver}")
private String driver;
@Value("${spring.account.url}")
private String url;
@Value("${spring.account.userName}")
private String userName;
@Value("${spring.account.password}")
private String password;
@Value("${jasypt.encryptorPwd.password}")
private String encPassword;
private Connection conn = null;
/**
* 解密
* @param pwd
* @return
*/
public String decryptPassword(String pwd){
String result = null;
BasicTextEncryptor textEnc = new BasicTextEncryptor();
textEnc.setPassword(encPassword);
if(PropertyValueEncryptionUtils.isEncryptedValue(pwd)){
result = PropertyValueEncryptionUtils.decrypt(pwd, textEnc);
}
return result;
}
public synchronized Connection getConnection() throws Exception {
Class.forName(driver); //加载驱动
if(null == conn){
//创建连接对象
conn = DriverManager.getConnection(url, userName, decryptPassword(password.substring(3)));
}
return conn;
}
/**
* 将ResultSet对象转换成domain的List
* @param rs
* @return
* @throws Exception
*/
public List<JournalInterface> bindDataToDTO(ResultSet rs) throws Exception {
JournalInterface dto = new JournalInterface();
Method[] methods = dto.getClass().getMethods();
List<JournalInterface> dtoList = new ArrayList();
ResultSetMetaData meta = rs.getMetaData();
JournalInterface obj = null;
while (rs.next()) {
// 获取实例对象
obj = dto.getClass().newInstance();
// 循环获取指定行的每一列的信息
for (int i = 1; i <= meta.getColumnCount(); i++) {
String colName = meta.getColumnName(i);
String setMethodName = "set" + colName;
//遍历Method
for (int j = 0; j < methods.length; j++) {
if (methods[j].getName().equalsIgnoreCase(setMethodName)) {
setMethodName = methods[j].getName();
// 获取当前位置的值,返回Object类型
Object value = rs.getObject(colName);
if(value == null){
continue;
}
//实行Set方法
try {
if(value instanceof BigDecimal){
//value = ((BigDecimal) value).toString();
value = Long.parseLong(value.toString());
}
//利用反射获取对象
//JavaBean内部属性和ResultSet中一致时候
Method setMethod = obj.getClass().getMethod(
setMethodName, value.getClass());
setMethod.invoke(obj, value);
} catch (Exception e) {
//JavaBean内部属性和ResultSet中不一致时候,使用String来输入值。
Method setMethod = dto.getClass().getMethod(
setMethodName, String.class);
e.printStackTrace();
}
}
}
}
dtoList.add(obj);
}
return dtoList;
}
/**
* 释放连接
* @param rs
* @param statement
* @param con
* @throws SQLException
*/
public void release(ResultSet rs, Statement statement, Connection con) throws SQLException{
try {
if(rs != null){
rs.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
try {
if(statement != null){
statement.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(con != null){
con.close();
}
}
}
}