I have a scenario where i need to call some service in the DAO layer to fetch some data based on a input coming from the database(in the resultset). so what best to way to instantiate the service. Inject in the DAO constructor or instanstiate inside the result set. see the below example for lucid understanding
public class ParticipationDao {
private ConnectionFactory connectionFactory'
private int userId;
/**
* Constructor which injects dependencies
*/
public ParticipationDao(String userId, ConnectionFactory connectionFactory) {
this.userId = userId;
this.connectionFactory = connectionFactory;
}
public List<Participation> getParticipantDetails(Integer studyId) throws StudyParticipationException {
List<Participation> participationList = new ArrayList<>();
String query = //some QUERY.....
try (Connection connection = connectionFactory.getConnection();
PreparedStatement stmt = connection.prepareStatement(query); ) {
stmt.setInt(1, studyId);
try (ResultSet rs = stmt.executeQuery();) {
while (rs.next() ) {
Participation p = new Participation();
//SOME OTHER ASSIGNMENTS ......
String modifiedUserId = rs.getString("ModifiedByID");
// TODO call some service here to get the username and assign to the setUserName method.
p.setUserName(assignHere);
participationList.add(p);
}
}
} catch (SQLException | ConnectionFactoryException e) {
throw new StudyParticipationException(e.getMessage(), e);
}
return participationList;
}
}
is it good way to inject the UserService in the DAO like below as this is not related to DAO logic so it is a good way to write like that.
public ParticipationDao(String userId, ConnectionFactory connectionFactory, UserService userService) {
this.userId = userId;
this.connectionFactory = connectionFactory;
this.userService = userService;
}
SUggest any good way. THank you