当前位置: 动力学知识库 > 问答 > 编程问答 >

java - JDBC Repository as singleton

问题描述:

I am writing a simple REST-Service which conntects to an Oracle DB via JDBC. I have a class called DatabaseRepository. This class is a singleton, I open the connection to the database at object creation and keep it alive all the time. In this class there are also methods which retrieve the data from the database and parse the result into objects.

My question now is, if what I do is good practice or not. My thought process was, that it would be better to keep a permanent connection (will be accessed like every 3 seconds) instead of creating a new connection for each call.

Code sample:

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;

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: