我的同事设计了在Struts2中对数据库连接使用单例模式,我问他如果连接只有一个实例,多用户下怎么办;他说Struts2可以确保多线程,我不太懂,这样设计行吗?
程序如下:
public class DatabaseInteraction {
private static Statement m_statement;
private static Connection m_connection;
private boolean m_stateConnection = false;
private boolean m_stateStatement = false;
private ProjectProperties m_databaseProperties;
private static final DatabaseInteraction INSTANCE = new DatabaseInteraction();
private DatabaseInteraction(){
try{
this.m_databaseProperties = ProjectProperties.getInstance();
String sDriver = m_databaseProperties.getM_driver();
Class.forName(sDriver);
String url = "";
url = "jdbc:mysql://" + m_databaseProperties.getM_hostname() + ":" + this.m_databaseProperties.getM_port() + "/" + m_databaseProperties.getM_sid() + "?"
+ "user=" + m_databaseProperties.getM_login() + "&password=" + m_databaseProperties.getM_password() + "&autoReconnect=true&failOverReadOnly=false";
m_connection = DriverManager.getConnection(url);
if(m_connection != null)
m_stateConnection = true;
m_statement = m_connection.createStatement();
if(m_statement != null)
m_stateStatement = true;
} catch (Exception e) {
Log4jInteraction.getInstance().getLogger().error("DatabaseInteraction.DatabaseInteraction(), database wrong!\n" + e.getMessage() + "\n" + e.getStackTrace());
//TODO:
//INSTANCE = null;
}
}
/*
returnning the only object for accessing the database
*/
public static DatabaseInteraction getInstance() {
return INSTANCE;
}
public Object execute(String query){
boolean bResult = false;
try{
bResult = m_statement.execute(query);
if (bResult){
return m_statement.getResultSet();
}else{
return new Integer(m_statement.getUpdateCount());
}
}
catch (CommunicationsException ce){
return "";
}
catch (SQLException e){
Log4jInteraction.getInstance().getLogger().error("DatabaseInteraction.execute, wrong!\n" + e.getMessage() + "\n" + e.getStackTrace() + "\n");
return e.getErrorCode() + "";
}
}
/*
close the database connection object
*/
public boolean close(){
try{
m_statement.close();
m_connection.close();
return true;
}
catch (Exception e){
Log4jInteraction.getInstance().getLogger().error("DatabaseInteraction.close, wrong!\n" + e.getMessage() + "\n" + e.getStackTrace());
return false;
}
}
// Getter and Setter
public boolean isM_stateConnection() {
return m_stateConnection;
}
public boolean isM_stateStatement() {
return m_stateStatement;
}
}