I am facing problem. We are writting Java application as school project and we are supposed to use threads. Obviously, the application is not as complex to require threads, but we have to have them.
We decided to use threads for database communication, but we are not sure, how to use them for single methods. We created Database Transfer Object with some methods to insert entities into DB. How to use Runnable
for single methods, please? To be more specific, we would like to create Runnable
in methods and then add it to thread pool, but then, we would be able to get returns back.
public class EmployeeDTO {
private Employee employee;
private Connection conn;
private int id_employee;
/**
* Database connection
* @throws ClassNotFoundException
* @throws SQLException
*/
public EmployeeDTO() throws ClassNotFoundException, SQLException {
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
public EmployeeDTO(Employee employee) throws ClassNotFoundException, SQLException {
this.employee = employee;
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
/**
* Insert new Employee into database and sets it's id
* @param emp
* @throws SQLException
*/
public void insertEmployee(Employee emp) throws SQLException {
setEmployee(emp);
PreparedStatement pr = conn.prepareStatement("INSERT INTO employees "
+ "(nickname,name,surname,password_emp) "
+ "VALUES (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
pr.setString(1, employee.getNickname());
pr.setString(2, employee.getName());
pr.setString(3, employee.getSurname());
pr.setString(4, employee.getPassword());
pr.executeUpdate();
ResultSet rs = pr.getGeneratedKeys();
while (rs.next()) {
employee.setId_employee(rs.getInt(1));
}
}
/**
* Delete an employee from database
* @param id
* @throws SQLException
*/
public void deleteEmployee(int id) throws SQLException {
PreparedStatement pr = conn.prepareStatement("DELETE FROM employees WHERE id_employee=?");
pr.setInt(1, id);
pr.executeUpdate();
}
}