属性名与字段名不相同
StudentDaoImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package com.node.dao.impl;
import java.util.List; import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import com.node.dao.StudentDao; import com.node.domain.Student; import com.node.util.SqlSessionUtil;
public class StudentDaoImpl implements StudentDao{
@Override public List<Student> selectStudentAll() { SqlSession session=SqlSessionUtil.getSession(); List<Student> list=session.selectList("selectStudentAll"); SqlSessionUtil.close(session); return list; } }
|
列名与实体类的属性名不同时,会导致数据封装失败
1:为查询语句定义别名,别名要求与实体类的属性名相同,这时MyBatis使用默认的封装规则封装数据
缺点:如果查询语句出现的次数过多,或者列数过多,别名写法繁琐并且失去了重用性
StudentDao.xml
1 2 3 4 5 6 7 8 9
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test"> <select id="selectStudentAll" resultType="student"> select id stuId, name stuName, age stuAge from student </select> </mapper>
|
2:resultMap:自定义封装规则
优点:这个封装规则可以重复使用
缺点:需要定义一个自定的封装规则,较为繁琐
StudentDao.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test">
<resultMap type="student" id="stu"> <id column="id" property="stuId"/> <result column="name" property="stuName"/> <result column="age" property="stuAge"/> </resultMap> <select id="selectStudentAll" resultMap="stu"> select * from student </select> </mapper>
|
3.使用Map集合作为记录的封装体
MyBatis返回Map
key: 字段名
value: 字段的值
优点:简单快捷
缺点:破坏了ORM对应关系,有点违反面向对象
StudentDao.xml
1 2 3 4 5 6 7 8 9
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test"> <select id="selectStudentAll" resultType="map"> select * from student </select> </mapper>
|