我试图在Spring启动应用程序中使用JdbcTemplate.query
获取表中的所有行。我使用MySQL数据库。我写了一个测试类来插入数据并通过它的主键查询插入的数据。它工作正常。但是我写的获取表中所有数据的测试用例返回一个空结果集,即使表中有一些数据也是如此。我可以使用MySQL控制台查询表,它同时显示表中的数据。我做错了什么?请帮忙。
用户存储库类中的代码
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional(readOnly = true)
public List<User> getAllUsers() {
return jdbcTemplate.query("SELECT * FROM db_users", new UserRowMapper());
}
@Transactional(readOnly = true)
public User getUserByUsername(String username) {
return jdbcTemplate.queryForObject("SELECT * FROM db_users WHERE username=?", new Object[]{username},
new UserRowMapper());
}
public User addNewUser(final User user) {
final String query = "INSERT INTO db_users(username,email,first_name,Last_name,password) values(?,?,?,?,?)";
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getEmail());
preparedStatement.setString(3, user.getFirstName());
preparedStatement.setString(4, user.getLastName());
preparedStatement.setString(5, user.getPassword());
return preparedStatement;
}
});
return user;
}
}
UserRowMapper类
class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet resultSet, int rowNum) throws SQLException {
User user = new User(resultSet.getString("username"), resultSet.getString("email"),
resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("password"));
return user;
}
}
测试用例中的代码;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTests {
@Autowired
private UserRepository userRepository;
@Test
public void createUserTest() {
User user = new User("testuser", "test@email.com", "Firstname", "Lastname", "password");
User savedUser = userRepository.addNewUser(user);
}
@Test
public void findUserByUsernameTest() {
User user = userRepository.getUserByUsername("testuser");
assertNotNull(user);
}
@Test
public void getAllUsersTest() {
List<User> users = userRepository.getAllUsers();
assertNotNull(users);
assertTrue(!users.isEmpty());
}
我得到的是,
getAllUsersTest(com.sol16.core.UserTests.UserRepositoryTest) Time elapsed: 0.026 sec <<< FAILURE!
junit.framework.AssertionFailedError: null
at junit.framework.Assert.fail(Assert.java:55)
at junit.framework.Assert.assertTrue(Assert.java:22)
at junit.framework.Assert.assertTrue(Assert.java:31)
at junit.framework.TestCase.assertTrue(TestCase.java:201)
at com.sol16.core.UserTests.UserRepositoryTest.getAllUsersTest(UserRepositoryTest.java:52)