将setObject隐藏,用反射获取model里面的数据
/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package com.eshore.fileExport;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
/**
* @author mercy
*
*/
public class Converter<T> {
public static <T> T convert2Bean(ResultSet rs, Class<T> bean) throws Exception {
Field[] fields = bean.getDeclaredFields();
T obj = bean.newInstance();
for (Field field : fields) {
String pname = field.getName();
BeanUtils.setProperty(obj, pname, rs.getObject(pname));
}
return obj != null ? obj : null;
}
public static <T> List<T> convert2BeanList(ResultSet rs, Class<T> bean) throws Exception {
Field[] fields = bean.getDeclaredFields();
List<T> lists = new ArrayList<T>();
String pName="";
String sqlName="";
while (rs.next()) {
T obj = bean.newInstance();
for (Field field : fields) {
String newName=getUnderlineString(field.getName());
if(newName.contains("_")){
String f1=newName.substring(0,newName.indexOf("_"));
String f2=newName.substring(newName.indexOf("_"),newName.indexOf("_")+1);
String f3=newName.substring(newName.indexOf("_")+1,newName.length());
System.out.println("f1:"+f1+",f2:"+f2+",f3:"+f3);
sqlName=f1+f2+f3;
}
pName = field.getName();
BeanUtils.setProperty(obj, pName, rs.getObject(sqlName));
}
lists.add(obj);
}
return lists != null ? lists : null;
}
public static char upperOrLower(char c){
if(c <= 90 && c >= 65){
c += 32;
} else if(c <= 122 && c >= 97){
c -= 32;
}
return c;
}
public static boolean isUpper(char c){
if(c <= 90 && c >= 65){
return true;
} else if(c <= 122 && c >= 97){
return false;
}
return false;
}
//由payType转为pay_type
public static String getUnderlineString(String str){
StringBuilder strs=new StringBuilder();
for(int i=0;i<str.length();i++){
if(isUpper(str.charAt(i))){
strs.append("_").append(upperOrLower(str.charAt(i)));
}else{
strs.append(str.charAt(i));
}
}
return strs.toString();
}
}
引用:
//获取前一天的所有计费数据
public List<BillData> queryBillList(int start,int size){
logger.info("query data...");
String sqlStr=sqlQuery+tableName;
List<BillData> billList=new ArrayList<BillData>();
ResultSet rs=null;
if(start!=0||size!=0){
sqlStr=sqlStr+" limit ?,?";
rs=util.Query(sqlStr,start,size);
}else{
rs=util.Query(sqlStr,null);
}
try {
return rs != null ? Converter.convert2BeanList(rs, BillData.class) : null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
//logger.info("sql:{}",sqlStr);
/*try {
while(rs.next()){
BillData bill=new BillData();
int i=1;
bill.setBusinessNumber(String.valueOf(rs.getObject(i++)));
bill.setPayType(Integer.parseInt(String.valueOf(rs.getObject(i++))));
bill.setAreaCode(String.valueOf(rs.getObject(i++)));
bill.setCreateTime(Timestamp.valueOf(String.valueOf(rs.getObject(i++))));
bill.setProductId(String.valueOf(rs.getObject(i++)));
bill.setProductSpecCode(String.valueOf(rs.getObject(i++)));
bill.setProductName(String.valueOf(rs.getObject(i++)));
bill.setPrice(Integer.parseInt(String.valueOf(rs.getObject(i++))));
bill.setBookType(Integer.parseInt(String.valueOf(rs.getObject(i++))));
bill.setAccType(String.valueOf(rs.getObject(i++)));
bill.setDeleCode(String.valueOf(rs.getObject(i++)));
billList.add(bill);
}
} catch (SQLException e) {
e.printStackTrace();
}
return billList;*/
}
如果还要再全一点的话就是把Conveter当成一个实现类,再写两个接口方法,并且加上数据库池。
DBHelper:
package dbhelper;
import java.io.PrintWriter;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import utils.XMLUtils;
public class DbHelper implements DataSource {
/**
* 用于暂时的存储数据库信息的Map
*/
private static Map<String, String> map = new HashMap<String, String>();
/*
* 既然是一个数据库连接池,就必须有许多的连接,所以需要使用一个集合类保存这些连接 (non-Javadoc)
*
* @see javax.sql.CommonDataSource#getLogWriter()
*/
public static LinkedList<Connection> connpool = new LinkedList<Connection>();
/**
* 通过XMLUtils实现对配置文件的信息读取,并实现DriverManager的使用
*
* @throws Exception
*/
static {
try {
Document document = XMLUtils.getDocument();
NodeList nodes = document.getElementsByTagName("database");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
switch (element.getAttribute("name")) {
case "mysql":
NodeList childs = element.getChildNodes();
for (int j = 0; j < childs.getLength(); j++) {
Node node = childs.item(j);
String nodename = node.getNodeName();
String nodevalue = node.getTextContent();
map.put(nodename, nodevalue);
}
break;
case "sqlserver":
break;
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* 预先注册数据源 ,保证数据可以正常的获取,每次查询的时候先调用这个方法
*
* @throws Exception
*/
public static void register() throws Exception {
String DRIVER = map.get("driver");
String URL = map.get("url");
String USER = map.get("user");
String PASSWORD = map.get("password");
Integer DATABASE_CONNECTION_POOL_SIZE = Integer.valueOf(map.get("poolsize"));
// 预先 添加驱动信息
Class.forName(DRIVER);
for (int index = 0; index < DATABASE_CONNECTION_POOL_SIZE; index++) {
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
connpool.add(conn);
}
}
/**
* 释放数据库连接对象
*
* @param conn
* 给定的数据库连接对象
*/
public static void release(Connection conn) {
try {
if (conn != null) {
connpool.add(conn);
}
} catch (Exception e) {
throw new RuntimeException("释放数据库连接对象时出错! :
" + e);
}
}
/**
* 释放数据库连接对象以及数据库查询对象
*
* @param conn
* 数据库连接对象
* @param stmt
* 数据库查询语句
*/
public static void release(Connection conn, Statement stmt) {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException("释放数据库查询对象Statement时出错! :
" + e);
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
release(conn);
}
public static void release(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (Exception e) {
throw new RuntimeException(" 关闭数据库结果集对象时出错!:
" + e);
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException("释放数据库查询对象Statement时出错! :
" + e);
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
release(conn);
}
/**
* 从数据库连接池中获取数据库连接对象,同时维护好池的内容实时更新
*/
@Override
public Connection getConnection() throws SQLException {
if (connpool.size() <= 0) {
throw new RuntimeException("数据库忙,请待会再试试吧!");
}
// 需要注意的是,不能使用get方式(这个方法知识返回一个引用而已),
// 应该在获取的同时,删除掉这个链接,之后再还回来.现在注意是返还给数据库连接池!!!
Connection conn = connpool.removeFirst();
MyConnection myconn = new MyConnection(conn);
// 从这里开始返回的就是一个数据库连接池对象的conn
return myconn;
}
///////////////////////////////////////////////////////////////////////// datasource接口的实现方法开始
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
// TODO Auto-generated method stub
return null;
}
///////////////////////////////////////////////////////////////////////// datasource接口的实现方法结束
/**
* 包装设计模式实现流程: 1.创建一个类,实现与被增强对象相同的接口 2.将被增强对象当做自定义类的一个成员变量
* 3.定义一个构造方法,将被增强对象传递进去 4.增强想要增强的方法,进行覆盖即可 5.对于不想被增强的方法,调用被增强对象的方法进行处理即可
*
* @author mercy
*
*/
/////////////////////////////////////////////////////////////////////// 使用包装设计模式,增强close方法的自定义类开始
class MyConnection implements Connection {
private Connection conn;
public MyConnection(Connection conn) {
this.conn = conn;
}
/**
* 自定义的包装设计模式类,增强close方法, 将数据库链接资源返还给数据库连接池,而不是数据库
*/
public void close() {
connpool.add(conn);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return this.conn.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return this.conn.isWrapperFor(iface);
}
@Override
public Statement createStatement() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStatement();
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareCall(sql);
}
@Override
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return this.conn.nativeSQL(sql);
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub
this.conn.setAutoCommit(autoCommit);
}
@Override
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getAutoCommit();
}
@Override
public void commit() throws SQLException {
// TODO Auto-generated method stub
this.conn.commit();
}
@Override
public void rollback() throws SQLException {
// TODO Auto-generated method stub
this.conn.rollback();
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return this.conn.isClosed();
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getMetaData();
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub
this.conn.setReadOnly(readOnly);
}
@Override
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return this.conn.isReadOnly();
}
@Override
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub
this.conn.setCatalog(catalog);
}
@Override
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getCatalog();
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub
this.conn.setTransactionIsolation(level);
}
@Override
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getTransactionIsolation();
}
@Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
this.conn.clearWarnings();
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStatement(resultSetType, resultSetConcurrency);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency);
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getTypeMap();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub
this.conn.setTypeMap(map);
}
@Override
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub
this.conn.setHoldability(holdability);
}
@Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getHoldability();
}
@Override
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return this.conn.setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return this.conn.setSavepoint(name);
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
this.conn.rollback(savepoint);
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
this.conn.releaseSavepoint(savepoint);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, autoGeneratedKeys);
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, columnIndexes);
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, columnNames);
}
@Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createClob();
}
@Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createBlob();
}
@Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return this.conn.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
// TODO Auto-generated method stub
this.conn.setClientInfo(name, value);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
// TODO Auto-generated method stub
this.conn.setClientInfo(properties);
}
@Override
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return this.conn.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getClientInfo();
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
// TODO Auto-generated method stub
return this.conn.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStruct(typeName, attributes);
}
@Override
public void setSchema(String schema) throws SQLException {
// TODO Auto-generated method stub
this.conn.setSchema(schema);
}
@Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getSchema();
}
@Override
public void abort(Executor executor) throws SQLException {
// TODO Auto-generated method stub
this.conn.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
// TODO Auto-generated method stub
this.conn.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getNetworkTimeout();
}
}
///////////////////////////////////////////////////////////////////////////// 包装设计模式结束
}
QueryRunner:
/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package dbhelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import handlers.BeanListHandler;
import handlers.Handler;
/**
* 业务核心类,实现自动化处理
*
* 包括自动化的增删改查
*
* @author 郭瑞彪
*
*/
public class QueryRunner {
/**
* 数据库查询,根据给定的查询条件 返回实例化之后的bean对象
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @param params
* 对应于SQL语句的参数描述
* @return 返回实例化Bean对象
* @throws Exception
*/
public <T> T query(Connection conn, String sql, Handler<T> handler, Object... params) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
}
ResultSet rs = ps.executeQuery();
return handler.handle(rs);
}
/**
* 数据库查询,根据给定的查询条件 返回实例化之后的bean对象
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @return 返回实例化Bean对象
* @throws Exception
*/
public <T> T query(Connection conn, String sql, Handler<T> handler) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
return handler.handle(rs);
}
/**
* 数据库查询,根据给定的查询条件 返回实例化之后的bean对象。此处对应于无参的处理方式
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @return 返回实例化Bean对象
* @throws Exception
*/
public <T> List<T> query(Connection conn, String sql, BeanListHandler<T> beanListHandler) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
return beanListHandler.handle(rs);
}
/**
* 数据库查询,根据给定的查询条件 返回封装了实例化的Bean对象的集合
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @param params
* 对应于SQL语句的参数描述
* @return 返回封装了实例化之后的bean集合
* @throws Exception
*/
public <T> List<T> query(Connection conn, String sql, BeanListHandler<T> beanListHandler, Object... params)
throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
/**
* fixed bug: 之前忘记了处理params对应于sql语句中的占位符表达了,所以可能导致sql语句未赋值的问题。现已解决。
*/
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
}
ResultSet rs = ps.executeQuery();
return beanListHandler.handle(rs);
}
/**
* 根据给定的参数实现向数据库中给定SQL语句的update,delete,insert 操作
*
* @param conn
* 数据库连接对象,用户不必关心其释放问题,这里自动将其释放
* @param sql
* 数据库查询语句
* @param params
* 对应于SQL语句占位符的参数列表
* @throws Exception
*/
public void update(Connection conn, String sql, Object... params) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
ps.executeUpdate();
DbHelper.release(conn, ps);
}
}
BeanHandler:
/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package handlers;
import java.sql.ResultSet;
import java.sql.SQLException;
import dbhelper.Conveter;
/**
* @author mercy
*
*/
public class BeanHandler<T> implements Handler<T> {
/**
* The Class of beans produced by this handler.
*/
private final Class<T> type;
/**
* Creates a new instance of BeanHandler.
*
* @param type
* The Class that objects returned from <code>handle()</code> are
* created from.
*/
public BeanHandler(Class<T> type) {
this.type = type;
}
/*
* (non-Javadoc)
*
* @see handlers.Handler#handle(java.sql.ResultSet)
*/
@Override
public T handle(ResultSet rs) {
try {
return rs.next() ? Conveter.convert2Bean(rs, this.type) : null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
BeanListHandler:
/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package handlers;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import dbhelper.Conveter;
/**
* @author mercy
*
*/
public class BeanListHandler<T> implements ListHandler<T> {
/**
* The Class of beans produced by this handler.
*/
private final Class<T> type;
/**
* Creates a new instance of BeanHandler.
*
* @param type
* The Class that objects returned from <code>handle()</code> are
* created from.
*/
public BeanListHandler(Class<T> type) {
this.type = type;
}
/*
* (non-Javadoc)
*
* @see handlers.Handler#handle(java.sql.ResultSet)
*/
@Override
public List<T> handle(ResultSet rs) throws SQLException {
try {
return rs != null ? Conveter.convert2BeanList(rs, this.type) : null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
XMLUtils:
/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package utils;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
/**
* 提供实现对db.cfg.xml文件的读和查找工作
*
* @author mercy
*
*/
public class XMLUtils {
// all the utils methods are static
public static Document getDocument() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("src/db.cfg.xml"));
return document;
}
public static void write2Xml(Document document) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
// wrapper the two arguments
DOMSource xmlSource = new DOMSource(document);
StreamResult targetResult = new StreamResult(new File("src/db.cfg.xml"));
transformer.transform(xmlSource, targetResult);
}
}
db.cfg.xml:
<?xml version="1.0" encoding="UTF-8" ?> <project> <database name="mysql"> <driver>com.mysql.jdbc.Driver</driver> <url>jdbc:mysql://192.168.115.72:8066/charge?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull</url> <user>root</user> <password>mysql</password> <poolsize>3</poolsize> </database> </project>
读取properties数据:
package com.eshore.fileExport;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReadSettingFileUtils {
private Logger logger=LoggerFactory.getLogger(this.getClass());
//private static final String fileName="D:/fileTest1/properties/fileSettings.properties";
//private static final String fileName="/home/billing/test/fileSettings.properties";
private static final String fileName="/home/ismp/write_charge/program/setting/fileSettings.properties";
private static final String projectFileName="/fileSettings.properties";
private static Properties properties = new Properties();
public Map<String, String> getFileContent(){
this.load();
Map<String, String> map = new HashMap<String, String>((Map) properties);
return map;
}
/**
* 从文件里面读取不到配置的话就读取项目路径下的配置
* @author mercy
*/
public void load() {
if (null != properties) {
InputStream in = null;
try {
/* 从文件路径获取配置文件 */
logger.debug("classpath not found filename!!");
in = new FileInputStream(fileName);
properties.load(in);
logger.info("load config file success!");
} catch (FileNotFoundException e) {
logger.warn(" server config file not found!");
in = this.getClass().getResourceAsStream(projectFileName);
try {
properties.load(in);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
logger.error("load config file error!", e);
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
logger.error("read config file error:", e);
}
}
}
}
}
}
MapRegister:
package com.eshore.fileExport;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MapRegister{
private Logger log=LoggerFactory.getLogger(this.getClass());
public static Map<String, String> map = new HashMap<String, String>();
public void init(){
map= new ReadSettingFileUtils().getFileContent();
for (Entry<String, String> entry : map.entrySet()) {
log.info("key:"+entry.getKey()+",value:"+entry.getValue());
}
}
public static Map<String, String> getMap() {
return map;
}
public static void setMap(Map<String, String> map) {
MapRegister.map = map;
}
}
propertis配置文件:
##driver name driver=com.mysql.jdbc.Driver ##database url ##acccount #user=root ##password #password=123456 ##table name url=jdbc:mysql://127.0.0.1:8066/charge?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull user=mycat password=test tableName=T_HB_DAY_FTP_MONITOR_DATA ##source file path #ftpDir=/home/ismp/write_charge/program/data/file/ ftpDir=D:/fileTest1/old/ ##bak file path #localBakDir=/home/ismp/write_charge/program/data/bak/ localBakDir=D:/fileTest1/new/ fileName=ETE_0_100003_CEI015_2_L_yyyymmdd_000000_20_0_xxx.json dataNum=50000