Boa noite.
Será que alguém pode me ajudar?
Estou tentando rodar o teste abaixo ele sempre retorna '"main" java.lang.NullPointerException: ' para o meu objeto no for mesmo tendo dados no banco e objeto estando setado.
TestaUserType.java
public class TestaUserType
{
public static void main(String[] args) throws SQLException
{
Database database = new Database();
try(Connection connection = database.getConnection()) {
List<UserTypes> userTypes = new UserTypesDAO(connection).list();
for (UserTypes userType : userTypes) {
System.out.println("Tipos cadastrados: " + userType.getTitle());
UsersDAO usersDAO = new UsersDAO(connection);
for(User user : usersDAO.search(userType)) {
System.out.println(user);
}
}
}
}
}
UsersDAO.java
public class UsersDAO
{
private Connection con;
public UsersDAO(Connection con)
{
this.con = con;
}
public void save(User user) throws SQLException
{
String SQL = "INSERT INTO `users`(`name`, `email`, `password`, `created_at`)";
SQL += " VALUES(?, ?, ?, ?)";
try ( PreparedStatement stmt = con.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS) ) {
Timestamp date = new Timestamp(new Date().getTime());
stmt.setString(1, user.getName());
stmt.setString(2, user.getEmail());
stmt.setString(3, user.getPassword());
stmt.setTimestamp(4, date);
stmt.execute();
}
}
public List<User> list() throws SQLException
{
List<User> users = new ArrayList<>();
String SQL = "SELECT * FROM users";
try(PreparedStatement stmt = con.prepareStatement(SQL)) {
stmt.execute();
getResult(users, stmt);
}
return users;
}
public List<User> search(UserTypes userType) throws SQLException
{
List<User> users = new ArrayList<>();
String SQL = "SELECT * FROM users WHERE type_id = ?";
try(PreparedStatement stmt = con.prepareStatement(SQL)) {
stmt.setInt(1, userType.getId());
stmt.execute();
getResult(users, stmt);
}
return null;
}
private void getResult(List<User> users, PreparedStatement stmt) throws SQLException
{
try(ResultSet resultSet = stmt.getResultSet()) {
while( resultSet.next() ) {
String name = resultSet.getString("name");
String email = resultSet.getString("email");
String password = resultSet.getString("password");
User user = new User(name, email, password);
users.add(user);
}
}
}
}
UserTypes.java
public class UserTypes
{
private final Integer id;
private final String title;
public UserTypes(Integer id, String title)
{
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public String getTitle() {
return title;
}
}
Desde já, obrigado :)