Search code examples
javadatabasejdbcibatistype-safety

What does it mean to do something in a "type safe" way?


An UPDATE statement can be configured in the Mapper XML file using the <update> element as follows:

<update id="updateStudent" parameterType="Student">
UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, PHONE=#{phone}
WHERE STUD_ID=#{studId}
</update>

We can invoke this statement as follows:

int noOfRowsUpdated =
sqlSession.update("com.mybatis3.mappers.StudentMapper.updateStudent", 
student);

Instead of invoking the mapped statement using namespace and the statement id, you can create a Mapper interface and invoke the method in a "type safe" way as follows:

package com.mybatis3.mappers;
public interface StudentMapper
{
int updateStudent(Student student);
}

You can invoke the updateStudentstatement using the Mapper interface as follows:

StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int noOfRowsUpdated = mapper.updateStudent(student);

My questions are: Why is the second way "type safe"? What does "type safe" mean here?


Solution

  • It is type-safe because type-mismatch errors will be detected at compile time and not runtime.

    In the first example, you can pass any Object that isn't of type Student to the update method, it will compile fine but will fail at runtime.

    In the second example you have to pass a valid Student object, otherwise, the code will fail to compile, and hence it's considered type-safe.