我正在编写一个简单的REST服务,它通过JDBC连接到Oracle DB。我有一个名为DatabaseRepository的类。这个类是一个单例,我在创建对象时打开与数据库的连接并始终保持活动状态。在这个类中,还有一些方法可以从数据库中检索数据并将结果解析为对象。
我现在的问题是,如果我做的是好的做法。我的思维过程是,保持永久连接(每3秒访问一次)更好,而不是为每个呼叫创建一个新连接。
代码示例:
private static DatabaseRepository instance = null;
private Connection connection = null;
private DatabaseRepository() throws ClassNotFoundException, SQLException {
Class.forName(DRIVER_STRING);
connection = DriverManager.getConnection(CONNECTION_STRING, USERNAME, PASSWORD);
// Add a shutdown hook, so the connection is closed when the applications stops
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}));
}
public static DatabaseRepository getInstance() throws ClassNotFoundException, SQLException {
if (instance == null) {
instance = new DatabaseRepository();
}
return instance;
}
public Entity getEntity(long entityId) throws SQLException {
if (entityId <= 0) {
throw new IllegalArgumentException("Entity id must be greater than 0!");
}
PreparedStatement statement = connection.prepareStatement("SELECT * FROM tbl_entity WHERE entity_id = ?");
statement.setLong(1, entityId);
ResultSet resultSet = statement.executeQuery();
// If no data was found, return null
if (!resultSet.next()) {
return null;
}
// Parse the values from the result set
Entity entity = resultSet. ...
statement.close();
resultSet.close();
return entity;
}