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
|
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是对应的文件名,上属为多文件添加样式的实现!
|
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对应的值
|