1. 程式人生 > >動態新建資料庫並連線

動態新建資料庫並連線

動態新建資料庫並連線,呼叫hibernate建表

CreateDataSource類:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import com.ioif.wha.cssp.util.ConfigHibernateHelper;
import com.ioif.wha.cssp.util.Constant;
import com.ioif.wha.hibernate.HibernateUtil;

public class CreateDataSource {

	/*** @param args */
	public static void main(String[] args) {
		// TODO Auto-generated method stub 
		String database = "test2";
		new CreateDataSource().getConn(database);
	}

	String mysqlDriver = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://192.168.1.201:3306/";
	String newUrl = "jdbc:mysql://192.168.1.201:3306/";
	String username = "sa";
	String password = "asdf123";
	Connection conn = null;
	Connection newConn = null;

	Connection getConn(String database) {
		// TODO Auto-generated method stub
		try {
			Class.forName(mysqlDriver);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block 
			e.printStackTrace();
		}

		try {
			String databaseSql = "create database " + database;
			conn = DriverManager.getConnection(url, username, password);
			System.out.println("資料庫連線成功!");
			Statement smt = conn.createStatement();
			smt.executeUpdate(databaseSql);
			
			//
			ConfigHibernateHelper chh = new ConfigHibernateHelper();
			java.util.List<Element> list = chh.read(Constant.CONFIG_FILE_LOCATION, Constant.PROPERTY_XPATH, Constant.MAPPING_XPATH);
			System.out.println("listSize---" + list.size());
			for (int i = 0; i < list.size(); i++) {
				 System.out.println("-----"+list.get(i)+"---------");
			}
			printValue(list);
			System.out.println("連線新的資料庫");
			// 模仿前臺傳送資料
			Map<String, String> paraMap = new HashMap<String, String>();
			paraMap.put(Constant.CONNECTION_URL,
					"jdbc:mysql://192.168.1.201:3306/"+database);
			// 修改快取配置
			HibernateUtil.getConfiguration(paraMap);
		

			// 改變重新XML
			changeDatabase(paraMap);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block   
			e1.printStackTrace();
		}

		return conn;
	}
	

	private static void changeDatabase(Map<String, String> paraMap) {
		// TODO Auto-generated method stub
		ConfigHibernateHelper helper = new ConfigHibernateHelper();
		// 讀取配置檔案
		List<Element> nodeList = helper.read(Constant.CONFIG_FILE_LOCATION,
				Constant.PROPERTY_XPATH, Constant.MAPPING_XPATH);
		System.out.println();
		System.out.println();
		System.out.println();
		// 修改前
		printValue(nodeList);
		System.out.println();
		System.out.println();
		System.out.println();
		nodeList = helper.replaceNewValue(paraMap, nodeList);
		helper.write(Constant.CONFIG_FILE_LOCATION, nodeList);
		// 修改後
		printValue(nodeList);
		System.out.println();
		System.out.println();
		System.out.println();

	}

	public static void printValue(List<Element> nodeList) {
		for (Element property : nodeList) {
			String name = property.attributeValue("name");
			String text = property.getText();
			if (Constant.CONNECTION_URL.equals(name)) {
				System.out.println("$" + name + " : " + text + "$");
			}
		}
	}

}

ConfigHibernateHelper類:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.xpath.DefaultXPath;


/**
 * 
 * 
 * 描述:<p>    讀取、重寫Hibernate配置檔案的工具類。</p>
 * 建立日期:2012-6-27 上午9:59:49<br>
 * @author:tianyj<br> 
 * @update:$Date$<br>
 * @version:$Revision$<br>
 * @since 版本號,用來指定該類是從整個專案的哪個版本開始加入到專案中的
 */
public class ConfigHibernateHelper {
	
	private SAXReader reader = null;
	private File file = null;
	private String url = null;
	private Document document = null;
	private List<Element> nodeList = null;
	
	private XMLWriter writer = null;
	
	
	/**
	 * 讀取XML檔案,返回根據過濾條件進行過濾的節點列表
	 * @param fileName 檔名稱
	 * @param xpath 過濾條件
	 * @return 節點元素列表
	 */
	public List<Element> read(String fileName, String pro_xpath, String map_xpath){
		reader = new SAXReader(); 
        try {
        	url = this.getFilePath(fileName);
        	file = new File(url);
            reader.setEntityResolver(new NoOpEntityResolver());
            document = reader.read(file);
            // 獲得hibernate-configuration:session-factory下的property屬性節點列表
            DefaultXPath propertyPath = new DefaultXPath(pro_xpath);
            nodeList = getNodeList(document, propertyPath);
            // 獲得hibernate-configuration:session-factory下的mapping屬性節點列表
            DefaultXPath mappingPath = new DefaultXPath(map_xpath);  
            List<Element> mappings = getNodeList(document, mappingPath);
            
            nodeList.addAll(mappings);
            
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return nodeList;
	}
	
	/**
	 * 根據條件返回節點列表
	 * @param document 文件變數
	 * @param propertyPath 過濾條件物件
	 * @return
	 */
	@SuppressWarnings("unchecked")
    private List<Element> getNodeList(Document document, DefaultXPath propertyPath) {
	    return propertyPath.selectNodes(document);
    } 
	
	/**
	 * 返回配置檔案的路徑
	 * @param fileName
	 * @return
	 */
	private String getFilePath(String fileName){
		return getClass().getClassLoader().getResource(fileName).getPath();
	}
	
	/**
	 * 替換從前臺傳遞的配置新的資料庫連線屬性
	 * @param paraMap 修改的資料key-value
	 * @param nodeList 節點列表
	 */
	public List<Element> replaceNewValue(Map<String,String> paraMap, List<Element> nodeList){
		// 迴圈需要修改的節點資訊,從前臺進行傳遞過來
		for(Map.Entry<String, String> entry : paraMap.entrySet()){
			for (Element property : nodeList) {  
                String name = property.attributeValue("name");
                // 過濾掉Mapping配置檔案節點
                String resource = property.attributeValue("resource");
                if(null != resource && "resource".equals(resource)){
                	break;
                }
                // 設定修改後的屬性值
                if(entry.getKey().equals(name)
                		|| entry.getKey().equals(name) || entry.getKey().equals(name)){
                	property.setText(entry.getValue());
                }
            }  
		}
		return nodeList;
	}
	
	/**
	 * 把配置資訊從新寫入
	 * @param nodeList
	 * @param fileName
	 * @return
	 */
	public boolean write(String fileName, List<Element> nodeList){
		url = this.getFilePath(fileName);
		// document
		Document document = DocumentHelper.createDocument();
		// 設定DocType
		document.addDocType("hibernate-configuration" , 
				"-//Hibernate/Hibernate Configuration DTD 3.0//EN" , 
				"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
		// hibernate-configuration  
        Element configuration = document.addElement("hibernate-configuration");  
        // session-factory  
        Element sessionfactory = configuration.addElement("session-factory");  
        sessionfactory.addComment("Database connection settings");
        // 新增屬性
        for(Element property : nodeList){
        	String name = property.attributeValue("name");
        	String resource = property.attributeValue("resource");
        	String text = property.getText();
        	// property節點操作方式
        	if(null != name && null!=text && !"".equals(name) && !"".equals(text)){
        		Element proElement = sessionfactory.addElement("property");  
        		proElement.addAttribute("name", property.attributeValue("name").trim());  
        		proElement.setText(property.getText().trim());
        	}else if(null != resource && !"".equals(resource)){
        		// mapping節點操作方式
        		Element mapping = sessionfactory.addElement("mapping");
        		mapping.addAttribute("resource", property.attributeValue("resource").trim());
        	}
        	
        }
        
        //設定輸出格式  
        OutputFormat format = new OutputFormat();  
        format.setEncoding("utf-8");  
        format.setIndent(true);  
        format.setLineSeparator("\n");  
        format.setNewlines(true);
        
        try {  
            writer = new XMLWriter(format);  
            writer.setOutputStream(new FileOutputStream(url));  
            writer.write(document);  
            writer.flush();  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if(writer != null) {  
                try {  
                    writer.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        } 
		return true;
	}
}

Constant類:
public class Constant {
	// Hibernate�����ļ����
	public static final String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
	// �����ļ���URL�������
	public static final String CONNECTION_URL = "hibernate.connection.url";
	// �����ļ�����ݿ��û���
	public static final String CONNECTION_USERNAME = "hibernate.connection.username";
	// �����ļ�����ݿ�����
	public static final String CONNECTION_PASSWORD = "hibernate.connection.password";
	public static final String PROPERTY_XPATH = "/hibernate-configuration/session-factory/property";
	public static final String MAPPING_XPATH = "/hibernate-configuration/session-factory/mapping";
	public static final String ALL_XPATH = "/hibernate-configuration/session-factory";
}

NoOpEntityResolver類:
import java.io.IOException;
import java.io.StringBufferInputStream;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class NoOpEntityResolver implements EntityResolver{

	@SuppressWarnings("deprecation")
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
	    // TODO Auto-generated method stub
	    return new InputSource(new StringBufferInputStream(""));
    }

}

HibernateUtil類:
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import com.ioif.wha.cssp.util.Constant;

public class HibernateUtil {
	private static SessionFactory sessionFactory;
	private static Configuration cfg;
	
	private static final Configuration getConfiguration(){
		cfg = new Configuration().configure();
		return cfg;
	}
	
	//使用ThreadLocal管理Session
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	static {
		try {
			//根據hibernate.cfg.xml建立SessionFactory
			sessionFactory = getConfiguration().buildSessionFactory();
		} catch (Throwable ex) {
			ex.printStackTrace();
			System.err.println("建立SessionFactory錯誤" + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}	
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}	
    public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			session = (sessionFactory != null) ? sessionFactory.openSession(): null;
			threadLocal.set(session);
		}
		return session;
	}    
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }
    
	
	/**
	 * 根據前臺傳遞的資料庫配置資訊進行立即修改
	 * @param paraMap
	 * @throws EXP_Base
	 */
	public static void getConfiguration(Map<String, String> paraMap){
		try {
			// 在Hibernate的快取中移除資料庫URL、使用者名稱、密碼配置資訊
			cfg.getProperties().remove(Constant.CONNECTION_URL);
			// 在Hibernate的快取中新增新的資料庫URL、使用者名稱、密碼配置資訊
			cfg.getProperties().setProperty(Constant.CONNECTION_URL,
					paraMap.get(Constant.CONNECTION_URL));
			/*
			 * 銷燬SessionFactory並釋放所有資源(快取,連線池等)。
			 */
			if (sessionFactory != null) {
				sessionFactory.close();
			}
			sessionFactory = cfg.buildSessionFactory();
			SchemaExport export = new SchemaExport(cfg);
			export.create(true, true);
			System.out.println("建表成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}