【发布时间】:2022-01-25 19:25:20
【问题描述】:
我使用 Spring 和 Thymeleaf 来显示我的数据库中有多少用户,代码如下所示
public long countUsers() {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
Long userCount = 0L;
try {
connection = ConnectionPool.getConnectionPool().getConnection();
statement = connection.prepareStatement(GET_USER_COUNT);
resultSet = statement.executeQuery();
resultSet.next();
userCount = resultSet.getLong("rowcount");
} catch (SQLException e) {
LOGGER.error(e);
} finally {
closeResource.close(statement);
closeResource.close(resultSet);
closeResource.close(connection);
ConnectionPool.getConnectionPool().releaseConnection(connection);
}
return userCount;
}
这很好用,我将它显示在网页上,例如“总共有 X 个用户”,但是当我在一秒钟内刷新页面 3 次时,计数变为 0 并且它停止工作。我收到这些消息
java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.
和
java.lang.NullPointerException: Cannot invoke "java.lang.AutoCloseable.close()" because "resource" is null
我正在使用控制器来计算我想要计数的位置
@GetMapping("/")
public String homepage(Model model) {
UserService userService = new UserService();
model.addAttribute("userCount", userService.countUsers());
return "index";
}
HTML 看起来像
<div>
<p>There are a total of <span th:text="${userCount}"></span> users created</p>
</div>
【问题讨论】:
-
不要这样做,您应该在应用程序配置中配置数据库,然后使用
@Autowired(或等效项)注入JdbcTemplate。 -
你可能想阅读Accessing Relational Data using JDBC with Spring(或者Accessing Data with JPA,如果你想直接使用JPA而不是SQL)。
标签: spring-boot nullpointerexception thymeleaf