我有一个 Java Swing 应用程序,它使用简单的单例模式访问 Postgres 数据库:
public class DatabaseConnection {
private static final String uname = "*******";
private static final String pword = "*******";
private static final String url = "*******************************";
Connection connection;
// load jdbc driver
public DatabaseConnection(){
try{
Class.forName("org.postgresql.Driver");
establishConnection();
} catch (ClassNotFoundException ce) {
System.out.println("Could not load jdbc Driver: ");
ce.printStackTrace();
}
}
public Connection establishConnection() {
// TODO Auto-generated method stub
try{
connection = DriverManager.getConnection(url, uname, pword);
} catch (SQLException e){
System.out.println("Could not connect to database: ");
e.printStackTrace();
}
return connection;
}
}
public class SingletonConnection {
private static DatabaseConnection con;
public SingletonConnection(){}
public static DatabaseConnection instance(){
assert con == null;
con = new DatabaseConnection();
return con;
}
}
这是我由 Pgadmin3 创建的用户表(因此丑陋的大写字母):
CREATE TABLE "user"
(
id serial NOT NULL,
"userRoleId" integer NOT NULL,
"employeeId" bigint NOT NULL,
"subjectId" bigint NOT NULL,
username text NOT NULL,
cryptpwd text NOT NULL,
"userStatusId" integer NOT NULL,
md5pwd text NOT NULL,
CONSTRAINT pk_user PRIMARY KEY (id),
CONSTRAINT "subjectId" FOREIGN KEY ("subjectId")
REFERENCES subject (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT user_employee_id FOREIGN KEY ("employeeId")
REFERENCES employee (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "user_userRole_id" FOREIGN KEY ("userRoleId")
REFERENCES "userRole" (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "user_userStatus_id" FOREIGN KEY ("userStatusId")
REFERENCES "userStatus" (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "unique_user_userName" UNIQUE (username)
)
由于此应用程序将在本地网络中的许多机器上运行,我希望每个特定用户只有一个连接实例。也就是说,如果 userA 从一台机器登录,而 userA 稍后从另一台机器登录,则通知应该出现在两台机器上,第二次登录可以选择继续连接 - 在这种情况下,现有连接将被删除/丢失的。
我想我必须在我的用户表中添加一个新列(logged_on boolean)......在这种情况下,通过查找logged_on 的值并采取适当的行动来处理第二次登录。我的问题是,我如何才能关闭第一个连接?如何在数据库级别最多维护一个连接 - 每个用户?