Parameter Passing in MyBatis Mapper Files
MyBatis Parameter Passing: Trensferring parameters from Java code to mapper.xml files.
Single Simple Parameter
When a DAO interface method contains only one simple parameter (Java primitive type or String), the placeholder #{any_text} can be used, and it is independent of the method's parameter name.
Mappper XML Configuration (StudentDao.xml)
<!-- namespace: unique namespace, recommended to use the fully qualified name of the DAO interface -->
<mapper namespace="com.lifang.dao.StudentDao">
<!--
<select>: represents a query operation, must contain a select statement
1. id: custom name for the SQL statement, must be unique, use the DAO interface method name
2. resultType: recommended to use the fully qualified class name
-->
<select id="selectStudentById" resultType="com.lifang.domain.Student">
SELECT id, name, email, age FROM student WHERE id = #{identifier}
<!-- MyBatis creates Student object and assigns property values -->
</select>
</mapper>
DAO Interface Definition
public interface StudentDao {
// Retrieve all records from Student table
List<Student> selectStudents();
int insertStudent(Student student);
Student selectStudentById(Integer id);
}
Test Implementation
@Test
public void testQueryById() {
SqlSession session = MybatisUtils.getSqlSession();
StudentDao dao = session.getMapper(StudentDao.class);
Student result = dao.selectStudentById(1002);
System.out.println(result);
}
ParameterType Attribute
The parameterType attribute specifies the data type of method parameters in the DAO interface. It accepts either fully qualified Java type names or MyBatis-defined aliases. This attribute is optional since MyBatis can infer parameter types through reflection.
<!--
parameterType: data type of DAO interface method parameter (optional)
Values can be Java fully qualified names or MyBatis aliases
Examples: parameterType="java.lang.Integer"
parameterType="int"
-->
<select id="selectStudentById" parameterType="int" resultType="com.lifang.domain.Student">
SELECT id, name, email, age FROM student WHERE id = #{identifier}
</select>
<!-- Equivalent without parameterType -->
<select id="selectStudentById" resultType="com.lifang.domain.Student">
SELECT id, name, email, age FROM student WHERE id = #{identifier}
</select>
Common MyBatis type aliases include:
- int or java.lang.Integer
- hashmap or java.util.HashMap
- list or java.util.ArrayList
The parameterType atttribute can be used with <select>, <insert>, <update>, and <delete> elements.