`
萝__卜
  • 浏览: 4960 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
珍藏
Hibernate动态连接多数据库改进篇


Hibernate根据方言dialect动态连接多数据库  的文章,发现效率不高,每次访问其他数据库,都要动态生成一个 sessionFactory实例,不算是个好的解决方法,后来查看hibernate源码,发现org.hibernate.cfg.Configuration类中有一个保护方法:

Java代码
protected void reset() {    
…    
}   
 故重写Configuration类,在动态的跳转不同数据库的时候,不用重新生成sessionFactory实例,发现效果不错。

故以此记录我的方法:

 

1. 自己重写的Configuration类,extends org.hibernate.cfg.Configuration :

 

Java代码
public class HibernateConfiguration extends org.hibernate.cfg.Configuration {    
   
    public HibernateConfiguration() {    
        super();    
    }    
   
    public void reset() {    
        super.reset();    
    }    
   
    public HibernateConfiguration(String dialect, String driverClass,    
            String ipAddress, String port, String dataBaseName,    
            String username, String password) throws HibernateException {    
        String connection_url = "";    
        if (dialect.indexOf("MySQL") > -1) {    
            connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;    
        } else if (dialect.indexOf("SQLServer") > -1) {    
            connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port    
                    + ";DataBaseName=" + dataBaseName;    
        } else if (dialect.indexOf("Oracle") > -1) {    
            connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port    
                    + ":" + dataBaseName;    
        } else {    
            throw new HibernateException("The dialect was not allowed.==fd=="   
                    + dialect);    
        }    
   
        super.setProperty("hibernate.dialect", dialect);    
        super.setProperty("hibernate.connection.url", connection_url);    
        super.setProperty("hibernate.connection.driver_class", driverClass);    
        super.setProperty("hibernate.connection.username", username);    
        super.setProperty("hibernate.connection.password", password);    
        // super.setProperty("hibernate.show_sql", "true");    
    }    
   
    public HibernateConfiguration(String dialect, String driverClass,    
            String ipAddress, String port, String dataBaseName,    
            String username, String password, String schema, String catalog)    
            throws HibernateException {    
        String connection_url = "";    
        if (dialect.indexOf("MySQL") > -1) {    
            connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;    
        } else if (dialect.indexOf("SQLServer") > -1) {    
            connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port    
                    + ";DataBaseName=" + dataBaseName;    
        } else if (dialect.indexOf("Oracle") > -1) {    
            connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port    
                    + ":" + dataBaseName;    
        } else {    
            throw new HibernateException("The dialect was not allowed.==fd=="   
                    + dialect);    
        }    
   
        super.setProperty("hibernate.dialect", dialect);    
        super.setProperty("hibernate.connection.url", connection_url);    
        super.setProperty("hibernate.connection.driver_class", driverClass);    
        super.setProperty("hibernate.connection.username", username);    
        super.setProperty("hibernate.connection.password", password);    
        super.setProperty("hibernate.default_schema", schema);    
        super.setProperty("hibernate.default_catalog", catalog);    
        // super.setProperty("hibernate.show_sql", "true");    
    }    
   
}   
 2. TempSessionFactory 的工厂类,这里把各个对象都变成了 static ,类也是static 类了,每次调用,都不用生成一个sessionFactory实例了,主要还是自己定义了一个reflashSessionFactory方法,对每次不同的数据库连接进行动态加载,见下:

 

Java代码
import org.hibernate.HibernateException;    
import org.hibernate.Session;    
import com.tools.hibernate.utils.HibernateConfiguration;    
   
public class TempSessionFactory {    
   
    /**   
     * Location of hibernate.cfg.xml file. Location should be on the classpath   
     * as Hibernate uses #resourceAsStream style lookup for its configuration   
     * file. The default classpath location of the hibernate config file is in   
     * the default package. Use #setConfigFile() to update the location of the   
     * configuration file for the current session.   
     */   
    private static String CONFIG_FILE_LOCATION = "/hibernate2.cfg.xml";    
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();    
    private static com.tools.hibernate.utils.HibernateConfiguration configuration = new HibernateConfiguration();    
    private static org.hibernate.SessionFactory sessionFactory;    
    private static String configFile = CONFIG_FILE_LOCATION;    
   
    static {    
        try {    
            configuration.configure(configFile);    
            sessionFactory = configuration.buildSessionFactory();    
        } catch (Exception e) {    
            System.err.println("%%%% Error Creating TempSessionFactory %%%%");    
            e.printStackTrace();    
        }    
    }    
   
    private TempSessionFactory() {    
    }    
   
    /**   
     * Returns the ThreadLocal Session instance. Lazy initialize the   
     * <code>SessionFactory</code> if needed.   
     *    
     * @return Session   
     * @throws HibernateException   
     */   
    public static Session getSession() throws HibernateException {    
        Session session = (Session) threadLocal.get();    
   
        if (session == null || !session.isOpen()) {    
            if (sessionFactory == null) {    
                rebuildSessionFactory();    
            }    
            session = (sessionFactory != null) ? sessionFactory.openSession()    
                    : null;    
            threadLocal.set(session);    
        }    
   
        return session;    
    }    
   
    /**   
     * Rebuild hibernate session factory   
     *    
     */   
    public static void rebuildSessionFactory() {    
        try {    
            // configuration.configure(configFile);    
            sessionFactory = configuration.buildSessionFactory();    
        } catch (Exception e) {    
            System.err.println("%%%% Error Rebuilding TempSessionFactory %%%%");    
            e.printStackTrace();    
        }    
    }    
   
    public static void reflashSessionFactory(    
            HibernateConfiguration tempConfiguration) {    
        try {    
            // configuration.configure(configFile);    
            if (tempConfiguration.getProperty("hibernate.dialect").equals(    
                    configuration.getProperty("hibernate.dialect"))    
                    && tempConfiguration    
                            .getProperty("hibernate.connection.url")    
                            .equalsIgnoreCase(    
                                    configuration    
                                            .getProperty("hibernate.connection.url"))    
                    && tempConfiguration    
                            .getProperty("hibernate.connection.username")    
                            .equals(    
                                    configuration    
                                            .getProperty("hibernate.connection.username"))    
                    && tempConfiguration    
                            .getProperty("hibernate.connection.password")    
                            .equals(    
                                    configuration    
                                            .getProperty("hibernate.connection.password"))) {    
   
                System.out.println("%%%% TempSessionFactory is created aready!!-fd %%%%");    
                // sessionFactory = configuration.buildSessionFactory();    
            } else {    
                closeSession();    
                closeSessionFactory();    
                configuration.reset();    
                configuration = tempConfiguration;    
                sessionFactory = configuration.buildSessionFactory();    
                System.out.println("%%%% TempSessionFactory is reflashed here!!-fd %%%%");    
            }    
        } catch (Exception e) {    
            System.err.println("%%%% Error Reflashing TempSessionFactory %%%%");    
            e.printStackTrace();    
        }    
    }    
   
    public static void closeSessionFactory() throws HibernateException {    
        try {    
            sessionFactory.close();    
        } catch (Exception e) {    
            System.err.println("%%%% Error Closing TempSessionFactory %%%%");    
            e.printStackTrace();    
        }    
    }    
   
    /**   
     * Close the single hibernate session instance.   
     *    
     * @throws HibernateException   
     */   
    public static void closeSession() throws HibernateException {    
        Session session = (Session) threadLocal.get();    
        threadLocal.set(null);    
   
        if (session != null) {    
            session.close();    
        }    
    }    
   
    /**   
     * return session factory   
     *    
     */   
    public static org.hibernate.SessionFactory getSessionFactory() {    
        return sessionFactory;    
    }    
   
    /**   
     * return session factory   
     *    
     * session factory will be rebuilded in the next call   
     */   
    public static void setConfigFile(String configFile) {    
        TempSessionFactory.configFile = configFile;    
        sessionFactory = null;    
    }    
   
    /**   
     * return hibernate configuration   
     *    
     */   
    public static HibernateConfiguration getConfiguration() {    
        return configuration;    
    }    
   
}   
  

3. 顺便发一下测试类,自己在不同服务器上面 建几个数据库,建几张测试表,就可以了:

 

Java代码
public static void main(String[] args) {    
    try{    
            
        String timeFormat = "yyyy-MM-dd HH:mm:ss";    
        SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);     
   
            
        HibernateConfiguration configuration1 = new HibernateConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",    
                "255.255.255.255","1433","dbname1","sa","sa");    
        System.out.println("hibernate.connection.url==1="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));    
        TempSessionFactory.reflashSessionFactory(configuration1);               
        System.out.println("hibernate.connection.url==2="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));    
            
        Session session1=TempSessionFactory.getSession();    
        Transaction tx1 = session1.beginTransaction();    
        Query query1 = session1.createSQLQuery("select  name as  aaa  from testtable ").setResultTransformer(    
                Transformers.ALIAS_TO_ENTITY_MAP);    
        Map obj1 = (Map)query1.setMaxResults(1).uniqueResult();    
        System.out.println("fd1111===="+obj1.get("aaa"));    
   
            
            
            
        System.out.println("hibernate.connection.url==3="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));    
        HibernateConfiguration configuration2 = new HibernateConfiguration("org.hibernate.dialect.Oracle10gDialect","oracle.jdbc.driver.OracleDriver",    
                "255.255.255.255","1521","orclDB1","username","passwd");                
        TempSessionFactory.reflashSessionFactory(configuration2);    
            
        System.out.println("hibernate.connection.url==4="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));    
        session1=TempSessionFactory.getSession();    
        tx1 = session1.beginTransaction();    
        Query query2 = session1.createSQLQuery("select testname1 AAA from testtable1 ").setResultTransformer(    
                Transformers.ALIAS_TO_ENTITY_MAP);    
        Map obj2 = (Map)query2.setMaxResults(1).uniqueResult();    
        System.out.println("fd2222===="+obj2.get("AAA"));    
            
            
            
            
        System.out.println("hibernate.connection.url==5="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));    
        HibernateConfiguration configuration3 = new HibernateConfiguration("org.hibernate.dialect.Oracle10gDialect","oracle.jdbc.driver.OracleDriver",    
                "255.255.255.255","1521","orclDB2","username","passwd");    
        TempSessionFactory.reflashSessionFactory(configuration3);    
        System.out.println("hibernate.connection.url==6="+TempSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));    
        session1=TempSessionFactory.getSession();    
        tx1 = session1.beginTransaction();    
        Query query3 = session1.createSQLQuery("select testname1 AAA from testtable2 ").setResultTransformer(    
                Transformers.ALIAS_TO_ENTITY_MAP);    
        Map obj3 = (Map)query3.setMaxResults(1).uniqueResult();    
        System.out.println("fd3333===="+obj3.get("AAA"));    
            
            
    }catch (Exception e) {    
        System.err.println(e);    
    }    
}   

原文来自:雨枫技术教程网 http://www.fengfly.com
原文网址:http://www.fengfly.com/plus/view-168846-1.html
Struts upload使用注意
actio  java代码
package com.struts.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class Upload extends ActionSupport {

	private File[] file;
	private String[] fileFileName;



	public String uploads() throws IOException {
		String path = ServletActionContext.getServletContext().getRealPath(
				"/upload");
		File files = new File(path);
		if (!files.exists())
			files.mkdir();

		for (int i = 0; i < file.length; i++) {
			if (null != file[i]) {
				FileUtils.copyFile(file[i], new File(files, fileFileName[i]));
			}
		}

		return "success";
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return "success";
	}

	public void setFile(File[] file) {
		this.file = file;
	}

	public File[] getFile() {
		return file;
	}

	public void setFileFileName(String[] fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String[] getFileFileName() {
		return fileFileName;
	}

}

jsp代码:


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>My JSP 'index.jsp' starting page</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

		<script type="text/javascript">

var i = 0, j = 1, k = 0;
function AddText(mytype) {
	i++;
	k = 0;
	var mytype, TemO = document.getElementById("add");
	var newInput = document.createElement("input");
	var newspan = document.createElement("span");
	var newline = document.createElement("br");
	TemO.appendChild(newline);

	newspan.type = "span";
	newInput.type = mytype;
	newInput.name = "file";
	newspan.appendChild( document.createTextNode("第"+i+"题 : ") );
	
	TemO.appendChild(newspan);
	TemO.appendChild(newInput);
	//获取每个问题的选项总数 k;
	var newline1 = document.createElement("br");
}
</script>
	</head>
	<body>
		<form action="upload" method="POST" enctype="multipart/form-data">
			<s:file  name="file" value=""></s:file>
			<input type="button" value="add" onclick="AddText('file')"/>
			<s:div id="add"></s:div>
			<input type="submit" value="tijiao"/>
		</form>
	</body>
</html>

HTTP Status 404 - There is no Action mapped for namespace /upload and action name .


    报这种错误的原因: 1  在于tomcat 清理缓存! 2,action代码中的file,和fileFileName是框架的规定,不能更改,file对应的是jsp中上传文本的name属性,fileFileName是对应的文件名,上属为多文件添加样式的实现!
Struts2 <s:select 表签用法
1.第一个例子:

<s:select list="{'aa','bb','cc'}" theme="simple" headerKey="00" headerValue="00"></s:select>

2.第二个例子:

<s:select list="#{1:'aa',2:'bb',3:'cc'}" label="abc" listKey="key" listValue="value" headerKey="0" headerValue="aabb">

3.第三个例子:

<%
java.util.HashMap map = new java.util.LinkedHashMap();
map.put(1,"aaa");
map.put(2,"bbb");
map.put(3,"ccc");
request.setAttribute("map",map);
request.setAttribute("aa","2");
%>
<s:select list="#request.map" label="abc" listKey="key" listValue="value"
value="#request.aa" headerKey="0" headerValue="aabb"></
s:select
>
headerKey headerValue 为设置缺省值
摘抄自 http://www.cnblogs.com/modou/articles/1326683.html

4.第四个例子

public class Program implements Serializable {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
private int programid;
private String programName;
public int getProgramid() {
return programid;
}
public void setProgramid(int programid) {
this.programid = programid;
}
public String getProgramName() {
return programName;
}
public void setProgramName(String programName) {
this.programName = programName;
}
}

在 xxx extends extends ActionSupport {
private List<Program> programs ;
public List<Program> getPrograms() {
return programs;
}
public void setPrograms(List<Program> programs) {
this.programs = programs;
}
}
在jsp页面
<s:select list="programs " listValue="programName " listKey="programid " name="program" id="program"
headerKey="0l" headerValue=" " value="bean.programid "
></s:select> 
红色部分为在action里面的list,黄色为<option value="xxx">value</option>对应bean里面的字段programName 
绿色为<option value="xxx",对应bean里面的字段programid

紫色为设定select被选中的值,s:select 会自动在 bean选中 key对应的值
Struts2用类获取表格值插入
Struts 2用类获取表格值插入	

public String addQuestion() {

		que.setQnnid(qun.getQnnid());

		new QuestionDao().addQuestion(que);
		ch.setQuestionid(new QuestionDao().maxQuestionId());
		String[] chs=ch.getOptions().split(",");
		for (int i = 0; i < chs.length; i++) {
			ch.setOptions(chs[i]);
			ch.setQnnid(qun.getQnnid());
			new ChooseDao().addChoose(ch);
		}
		
		return "quesionmain";
	}


<form action="Admin_addQuestion" method="post">
				<input type="text" name="qun.qnnid"
					value="<s:property value='qun.qnnid'/>" />
				<table>
					<tr>
						<td>
							问卷
							<s:property value='qun.qnnname' />
						</td>
					</tr>
					<tr>
						<td>
							问题
						</td>
						<td>
							<input type="text" name="que.title">
						</td>
					</tr>
					<tr>
						<td>
							选项1:
						</td>
						<td>
							<input type="text" name="ch.options">
						</td>
					</tr>
					<tr>
						<td>
							选项2:
						</td>
						<td>
							<input type="text" name="ch.options">
						</td>
					</tr>
					<tr>
						<td>
							选项3:
						</td>
						<td>
							<input type="text" name="ch.options">
						</td>
					</tr>
					<tr>
						<td>
							选项4:
						</td>
						<td>
							<input type="text" name="ch.options">
						</td>
					</tr>
					<tr>
						<td>
							<input type="submit" value="添加" />
						</td>
					</tr>
				</table>
			</form>
Struts2通配符问题
<package name="default" namespace="/" extends="struts-default">


		<action name="*News" class="com.news.action.ProcessNews" method="{1}News">
			<result name="{1}News">/admin/{1}news.jsp</result>
			<result name="error">/admin/errornews.jsp</result>
		</action>

		<action name="mainNews" class="com.news.action.MainNews">
			<result name="success">/admin/mainnews.jsp</result>
			<result name="error">/admin/errornews.jsp</result>
		</action>
		
		<action name="login" class="com.news.action.LoginAction">
			<result name="error">/admin/errornews.jsp</result>
			<result name="success" type="redirect">mainNews</result>
		</action>
		
	</package>
scala 配置方法
这里的环境配置是基于JVM的Scala的配置,基于.net的我没安装过 ╮(╯▽╰)╭这里说的是Windows下怎么安装,ubuntu下直接 sudo apt-get install scala就可以了。

首先是安装Java,并配置Java环境变量。

首先下载Java安装包: Java.Oracle.com 中查找并下载,我这里下载的是最新版本。

配置环境变量:

在桌面我的电脑上点右键,属性;


Win7下点击左侧的高级系统设置(XP跳过这一步)


点击环境变量:


添加点击新建 添加JAVA_HOME变量指向你Java的安装路径


添加CLASSPATH .;%JAVA_HOME%\lib  (注意一开始的.;号)
在Path路径中添加 ;%JAVA_HOME%\bin (注意一开始的;号)

在运行下,输入cmd 打开命令窗口 输入 java 与 javac 如果都正常,没有提示命令找不到则Java配置完成。

=======SCALA配置====================================================================

下载安装Scala,双击安装。win下下载msi安装包吧,比较方便。

环境变量中添加 %SCALA_HOME% 指向Scala安装路径

Path在安装是应该已经自动添加到最后了理论上不需要在修改。

命令窗口输入 scala 应该可以看到欢迎信息。

如果提示 此时不应有 XXX,尝试把你的Path中的Java路径直接替换成完成的Java路径,例如将%JAVA_HOME%\bin 替换成 C:\Java\bin

如果还是其他的提示。。。好吧,尝试着挨个删除你的环境变量吧,基本上都是环境变量的问题。。。╮(╯▽╰)╭

个人Win7 64/32都安装成功。

========IDE 插件===================================================================

Eclipse 插件:http://download.scala-ide.org/releases-29/stable/site

NetBeans 插件:http://wiki.netbeans.org/Scala

IntelliJ插件  http://plugins.intellij.net/plugin/?id=1347
Struts action跳转到另一个action
<struts>
	<package name="com" extends="struts-default">
		<action name="a1" class="Action1">
			<result name="sucess" type="chain">a2</result>
		</action>

		<action name="a2" class="Action2">
			<result name="sucess" type="chain">
				<param name="actionName">a3</param>
				<param name="namespace">tb</param>
			</result>
		</action>
	</package>

	<package name="tb" extends="struts-default">
		<action name="a3" class="Action3">
			<result name="sucess">/index.jsp</result>
		</action>
	</package>
	
</struts> 

<-redirect->
<-redirectaction->
Global site tag (gtag.js) - Google Analytics