动态新建数据库并连接

动态新建数据库并连接,调用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();
		}
	}
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值