条条|MyBatis学习笔记5——返回值

5.1MyBatis返回值

mybatis执行了sql语句,得到java对象,即把查询到的数据赋值给对应java对象的对应属性

ResultType(结果类型)

指sql语句执行完毕后, 数据转为的java对象, java类型是任意的;resultType结果类型的它值 1. 类型的全限定名称 2. 类型的别名, 例如 java.lang.Integer别名是int

例如查询目标表的数量,但一般推荐使用类型的全限定名称
<select id="selectCount" resultType="int">
    select count(*) from student
</select>
处理方式
  1. mybatis执行sql语句, 然后mybatis调用类的无参数构造方法,创建对象
  2. mybatis把ResultSet指定列值付给同名的属性
    该形式等同于jdbc的
    ResultSet rs = executeQuery(" select id,name, email,age from student" )
        while(rs.next()){
             Student  student = new Student();
            student.setId(rs.getInt("id"));
            student.setName(rs.getString("name"))
        }
    

给定义自定义类型起别名

给自定义类型起别名就可以用别名来代替全限定名称,一般要求别名短小,易记和准确

1.package
主配置文件文件
<typeAliases>
    <package name="com.mybatis.domain"/>
</typeAliases>
mapper文件
<select id="selectStudentObject" resultType="Student">
    select id,name,email,age from student where name=#{paramName} or age=#{paramAge}
</select>

name代表类所在的包的全限定名称,该包下的所有类的名称等于别名,我们就可以直接在mapper中直接把类名当别名来用了

2.typeAliases
主配置文件文件
<typeAliases>
    <typeAlias type="com.mybatis.domain.Student" alias="stu"/>
</typeAliases>
mapper文件
<select id="selectStudentObject" resultType="stu">
    select id,name,email,age from student where name=#{paramName} or age=#{paramAge}
</select>
一般用package多一点,不过还是建议直接使用全限定名称,以防混淆和产生安全问题

resultMap(结果映射)

resultMap指定列名和java对象的属性对应关系,当列名和属性名不一样时,一定使用resultMap;
注:resultMap和resultType不要一起用,二选一

mapper文件
<resultMap id="studentMap" type="com.mybatis.domain.Student">
<!--
     主键用id,非主键用result
     column代表列名,property代表属性名
 -->
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="email" property="email"/>
    <result column="age" property="age"/>
</resultMap>
<select id="selectByMap" resultMap="studentMap">
    select id,name,email,age from student
</select>
解决列名和属性名不一致的另一种解决办法(给列名起别名)

设我们的属性名都是stu+...
==>可以把select id,name,email,age from student改成select id as stuid,name as stuname,email as stuemail,age as stuage from student

模糊查询

在数据库中我们要查询name带有a的sql语句是select * from student where name like "%a%",那在mybatis中如何进行模糊查询呢?

  1. java代码中指定like内容
    mapper文件
    <select id="selectMo" resultType="com.mybatis.domain.Student">
        select id,name,email,age from student where email like #{name}
    </select>
    
    调用类中
    SqlSession sqlSession= MyBatisUtils.getSqlSession();
    StudentDao dao=sqlSession.getMapper(StudentDao.class);
    String m="%qq%";
    List<Student> l=dao.selectMo(m);
    for (Student s: l
    ) {
        System.out.println(s);
    }
    
  2. 在mapper文件中拼接
    mapper文件
    <select id="selectMo" resultType="com.mybatis.domain.Student">
        select id,name,email,age from student where email like "%" #{name} "%"
    </select>
    

条条:该学习笔记是记录了我的学习过程,学习自动力节点c语言中文网,有不对的地方欢迎指出

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。