XXMapper.xml文件
1、id:标识映射文件中的sql;
将sql语句封装到mapped statement对象中,所以将id称为statement的id。
2、parameterType:指定输入参数类型
3、parameterMap:同parameterType,旧版本
4、resultType:指定sql输出结果所映射的java对象类型;
select指定resultType,表示将单条记录映射成的java对象。使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可映射成功。
5、resultMap:用于高级输出结果映射。
使用方法:定义resultMap,使用resultMap作为statement的输出映射类型。
<resultMap type=”user” id=”userResultMap”>
<!—id表示查询结果集中唯一标识
column:查询出来的列名
property:type指定的pojo类型中的属性名
最终resultMap对column和property作一个映射关系(对应关系) -->
<id column=”id_” property=”id”/>
<!—result:对普通名映射定义 最终resultMap对column和property作一个映射关系(对应关系) -->
<result column=”username_” property=”username”/>
</resultMap>
<select id=”findUserByResultMap” parameterType=”int” resultMap=”userResultMap”>
SELECT id id_, username username_ FROM USER WHERE id=#{value}
</select>
6、#{}表示一个占位符
#{id}其中的id表示接受输入的参数,参数名称是id;如果输出参数是简单类型,#{}中的参数名可以任意,可以是value或其他名称。
如果接受pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性的方法获取对象属性值。
<select id=”findUserById” parameterType=”int” resultType=”cn.itcast.mybatis.po.User”>
SELECT * FROM USER WHERE id = #{id}
</select>
<sql id="Base_Column_List" >
ID, DEPT_NAME, DEPT_NO, FID, WEIGHT, CREATE_DATE
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap"
parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from SYS_MAN_DEPARTMENT
where ID = #{id,jdbcType=VARCHAR}
</select>
7、${}表示一个拼接符
将接受到的内容不加任何修饰拼接在sql中;但是会引起sql注入,不建议使用。
${value}接受输入参数的内容,如果传入类型是简单类型,${}中只能使用value;如果接受pojo对象值,通过OGNL读取读取对象中的属性值,通过属性.属性.属性的方法获取对象属性值。
模糊查询:
<select id=”findUserByName” parameterType=”java.lang.String”
resultType=”cn.itcast.mybatis.po.User”>
SELECT * FROM USER WHERE username LIKE ‘%${value}%’
</select>
8、关于主键
A)自增主键:主键id如果是自增的,则不设置,即使设置了也没效果。
通过mysql函数获取到刚插入记录的自增主键:LAST_INSERT_ID(),是insert之后调用此函数。
B)非自增主键:使用mysql的uuid()函数生成主键,需要修改表中id字段类型为String,长度设置为35位。执行思路:先通过uuid()查询到主键,将主键插入到sql语句中。
C)通过oracle的序列生成主键:
根据id更新用户:
<update id=”updateUser” parameterType=”cn.itcast.po.user”>
update user set username=#{username}, birthday=#{ birthday }, address=#{address} where id=#{id}
</update>