以“类型安全”的方式做某事意味着什么?

时间:2023-01-11 16:03:52

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

可以使用 元素在Mapper XML文件中配置UPDATE语句,如下所示:

<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:

您可以创建Mapper接口并以“类型安全”方式调用该方法,而不是使用命名空间和语句ID调用映射语句,如下所示:

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

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

您可以使用Mapper接口调用updateStudentstatement,如下所示:

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?

我的问题是:为什么第二种方式是“类型安全”? “类型安全”在这里意味着什么?

1 个解决方案

#1


3  

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.

在第一个示例中,您可以将任何非Student类型的Object传递给update方法,它将编译正常但在运行时将失败。

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.

在第二个示例中,您必须传递一个有效的Student对象,否则代码将无法编译,因此它被认为是类型安全的。

#1


3  

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.

在第一个示例中,您可以将任何非Student类型的Object传递给update方法,它将编译正常但在运行时将失败。

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.

在第二个示例中,您必须传递一个有效的Student对象,否则代码将无法编译,因此它被认为是类型安全的。