parameterType(参数类型)
-
当参数类型是对象数据类型时,在parameterType上写上参数名,根据参数获取他们的get()方法,然后用#{} 传入属性名,mybatis就会自动映射到数据库的字段中去。
这里要提到一点:OGNL表达式(Object Graphic Navigation Language)
它是通过对象的取值方法来获取数据,在写法上把get给省略了。
比如:我们获取用户的名称
---------------------------------- 类中的写法:user.getUsername();
-----------------------------------OGBL表达式的写法:user.username
mybatis中为什么能直接写username,而不用user呢,
---------------------------------- 因为在parameterType中已经提供了属性所属的类,所以此时不用写对象名
当POJO中的属性也是实体类时
例如:
package com.lanou.test.dao;
public class POJO {
private int id;
//实体类属性
private User user;
}
此时mapper.xml文件中应该这样写
<select id="findAll" parameterType="com.lanou.test.dao.POJO" resultType="com.lanou.test.dao.POJO">
select * from user where username=#{user.username}
</select>
#{user.username}中的user因为是parameterType中POJO用OGNL获得到的,但是user中的属性(username)却是映射不上的,所以要再用OGNL获得一次。
- 当参数类型是基本数据类型和String的时候(就意味着传递的参数只有一个),所以#{} 中的名字可以随便写。其实这时候parameterType上参数的类型都可以不用写,但是为了规范,还是写上比较好。
resultType(返回值类型)
-
当数据库的字段名和POJO中的属性名不一致的时候,使用标签resultMap
mapper.xml的配置文件
<?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="com.lanou.test.mapper.IUserMapper">
<!-- 配置数据库字段名和实体类的属性名对应关系 -->
<resultMap id="userMap" type="com.lanou.test.bean.User">
<!-- 主键字段的对应-->
<id property="userid" column="id"></id>
<!-- 非主键字段的对应-->
<result property="username" column="username"></result>
<result property="useraddress" column="address"></result>
<result property="usersex" column="sex"></result>
<result property="userbirthday" column="birthday"></result>
</resultMap>
<select id="findAll" resultMap="userMapre">
select * from user
</select>
</mapper>