I am using spring-boot, spring data, and Java 6. Here is an example from a business layer to save student details.
Srvice interface:
public interface StudentService
{
public StudentDTO save(Integer stdId, Integer divisionId, StudentDTO studentDTO);
}
Service implementation:
@Service("studentService")
public class StudentServiceImpl implements StudentSerivce
{
@Autowire
private StudentDAO studentDAO;
@Autowire
private STDDAO stdDAO;
@Autowire
private DivisionDAO divisionDAO;
@Autowire
private TSBeanMapper beanMapper;
@Override
public StudentDTO save(Integer stdId, Integer divisionId, StudentDTO studentDTO)
{
STDEntity std = stdDAO.findOne(stdId);
if (std == null)
{
throw new BadRequestException("Invalid standard");
}
DivisionEntity division = divisionDAO.finsOne(divisionId);
if (division == null)
{
throw new BadRequestException("Invalid division");
}
StudentEntity student = beanMapper.map(studentDTO, StudentEntity.class);
student.setSTD(stdEntity);
student.setDivision(divisionEntity);
return beanMapper(studentDAO.save(studentEntity), StudentDTO.class);
}
}
For stdId
and divisionId
, I have called findOne
and checked against null
.
I would prefer that findOne
throws an exception rather that return null
for my case. But in this bug report it looks like currently it's not possible.
As for those 3 lines:
- Fetch entity
- Check
null
ifNull
then throw an exception
These lines of code are needed in other services for stdId
and divsionID
.
What is the best practice to separate those validations from serviceImpl
and put it in other reusable components?