MyBatis Course Mapping: Implementing getCourseById with ResultMap
Lily built a MyBatis application and created an entity class 'Course' in the application. The code is as follows:
public class Course {
private String cid;
private String cname;
private Integer credits;
//getter and setter omitted here
}
In addition, she created a data table named 'course' in the database, which contains three fields: 'courseId', 'courseName', and 'courseCredits'. Now, she has created a 'CourseMapper' interface and added a query operation with code as follows:
public interface CourseMapper {
Course getCourseById(String id);
}
To implement the query operation, Lily needs to add a 'CourseMapper.xml' file and implement mapping of the 'getCourseById' method. The correct mapping code snippet to realize the functionality described is:
<select id="getCourseById" resultMap="courseMap">
select * from course where courseId = #{id}
</select>
<resultMap id="courseMap" type="com.model.Course">
<id property="cid" column="courseId"/>
<result property="cname" column="courseName"/>
<result property="credits" column="courseCredits"/>
</resultMap>
Explanation:
- The
<select>element specifies the SQL statement to be executed. - The
#{}syntax is used to specify a parameter placeholder. In this case, the parameter is 'id' and it should be of type String. - The
resultMapattribute is used to specify the result mapping for the query. - The
<resultMap>element specifies how the query results should be mapped to the entity properties. - The 'id' element specifies the primary key property of the entity.
- The 'result' elements specify the other properties of the entity.
- The 'column' attribute is used to specify the column names in the database table.
- The 'property' attribute is used to specify the property names in the entity class.
原文地址: https://www.cveoy.top/t/topic/oCFj 著作权归作者所有。请勿转载和采集!