I'm developing a web application with spring framework and mybatis.
In most cases(at least for me), DAO's methods are very short something like this:
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
public User getUser(String userId) {
return (User) getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
}
}
So basically, I need to write a method(e.g. getUser(String userId)
) in DAO for each query which is being forwarded to service objects where it is being used. It seems unnecessarally redundunt to me.
My co-worker is trying to make it simple. He wrote CommonDao
like this:
@Repository
public class CommonDao {
@Autowired
private SqlSessionTemplate sqlSession;
public Object insert(String queryId, Object params) {
return sqlSession.insert(queryId, params);
}
public Object update(String queryId, Object params) {
return sqlSession.update(queryId, params);
}
public Object delete(String queryId, Object params) {
return sqlSession.delete(queryId, params);
}
public Object selectOne(String queryId) {
return sqlSession.selectOne(queryId);
}
public Object selectOne(String queryId, Object params) {
return sqlSession.selectOne(queryId, params);
}
}
So we can use these methods in services like:
@Service
public class CrudService {
...
@Autowired
private CommonDao commonDao;
...
public UserDto selectUser(Integer userId) {
...
UserDto userDto = (UserDto) commonDao.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
...
}
}
I'm kinda like this approch since it makes codes simpler. But I'm not sure it is a good prectice to follow.