【MyBatis】4、ResultType与ResultMap

【MyBatis】4、ResultType与ResultMap,第1张

封装MyBatis输出结果
  • 1、ResultType
    • 简单类型
    • 对象类型
  • 2、ResultMap

1、ResultType

MyBatis执行sql语句,得到ResultSet转换对象,使用全类型限定名或别名

ResultSet结果类型,指sql语句执行完毕后,数据转为Java,其类型是任意的。
处理办法

  1. Mybatis执行sql语句,然后Mybatis调用类的无参构造方法,创建对象.
  2. MybatisResultSet指定列值付给同名的属性

简单类型

接口

int countStudent();

Mapper文件


<select id="countStudent" resultType="int">
   select count(*) from student
select>

测试方法

@Test
public void testRetunInt(){
     int count = studentDao.countStudent();
     System.out.println("学生总人数:"+ count);
}
对象类型

接口

Student selectById(int id);

实体类对象

private String name;
private  String age;
// set get  toString() 等方法

Mapper文件

<select id="selectById" resultType="com.bjpowernode.domain.Student">
   select id,name,email,age from student where id=#{studentId}
select>

框架的处理方式:
使用构造方法创建对象,条用 setXXX()给属性赋值,相当于Student student = new Student();,Student 中变量的名字需要和数据库表中的字段名一致。

Sql字段名Java对象方法
idsetId()
namesetName()
emailsetName()
agesetAge()

Dao接口方法方法返回时集合类型,需要指定集合中的类型,不是集合本身


2、ResultMap

resultMap 可以定义sql的结果和java对象属性的映射关系。更灵活的把列值赋值给指定属性,常用在列明和Java对象属性名不一样的情况

  1. 先定义 resultMap 指定列明和属性名的对应关系
  2. resultType 替换为 resultMap

接口

List<Student> selectUseResultMap(QueryParam param);

mapper文件


<resultMap id="studentMap" type="com.bjpowernode.domain.Student">
   
   <id column="id" property="id" />
   
   <result column="name" property="name"/>
   <result column="email" property="email" />
   <result column="age" property="age" />
resultMap>


<select id="selectUseResultMap" resultMap="studentMap">
   select id,name,email,age from student where name=#{queryName} or age=#{queryAge}
select>

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/724328.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存