<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<!-- mapper 为根元素节点, 一个namespace对应一个dao -->
<mapper namespace="com.zly.dao.UserDao">
<insert
<!-- 1. id (必须配置)
id是命名空间中的唯一标识符,可被用来代表这条语句。
一个命名空间(namespace) 对应一个dao接口,
这个id也应该对应dao里面的某个方法(相当于方法的实现),
因此id 应该与方法名一致 -->
id="insertUser"
<!-- 2. parameterType (可选配置, 默认为mybatis自动选择处理)
将要传入语句的参数的完全限定类名或别名, 如果不配置,
mybatis会通过ParameterHandler 根据参数类型默认选择合适的
typeHandler进行处理
parameterType 主要指定参数类型,可以是int, short, long,
string等类型,也可以是复杂类型(如对象) -->
parameterType="com.demo.User"
<!-- 3. flushCache (可选配置,默认配置为true)
将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和
二级缓存都会被清空,默认值:true(对应插入、更新和删除语句) -->
flushCache="true"
<!-- 4. statementType (可选配置,默认配置为PREPARED)
STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别
使用 Statement,PreparedStatement 或 CallableStatement,
默认值:PREPARED。 -->
statementType="PREPARED"
<!-- 5. keyProperty (可选配置, 默认为unset)
(仅对 insert 和 update 有用)唯一标记一个属性,MyBatis 会通过
getGeneratedKeys 的返回值或者通过 insert 语句的 selectKey
子元素设置它的键值,默认:unset。如果希望得到多个生成的列,
也可以是逗号分隔的属性名称列表。 -->
keyProperty=""
<!-- 6. keyColumn (可选配置)
(仅对 insert 和 update 有用)通过生成的键值设置表中的列名,
这个设置仅在某些数据库(像 PostgreSQL)是必须的,
当主键列不是表中的第一列的时候需要设置。如果希望得到多个生成的列,
也可以是逗号分隔的属性名称列表。 -->
keyColumn=""
<!-- 7. useGeneratedKeys (可选配置, 默认为false)
(仅对 insert 和 update 有用)这会令 MyBatis 使用 JDBC 的
getGeneratedKeys 方法来取出由数据库内部生成的主键
(比如:像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增
字段),默认值:false。 -->
useGeneratedKeys="false"
<!-- 8. timeout (可选配置, 默认为unset, 依赖驱动)
这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。
默认值为 unset(依赖驱动)。 -->
timeout="20"
<!-- 9. resultType(可选配置,有返回值的时候得有) -->
resultType="User"
<!-- 10.resultMap 外部resultMap的命名引用,不可和resultType同时使用 -->
<if标签>
<!--统计用户数量-->
<select id="countUserByNameAndGender" parameterType="com.liuyanzhao.mybatis.po.User" resultType="int">
SELECT COUNT(*) FROM user
<!--where标签可以去掉首部的AND符号-->
<where>
<if test="gender!=null and gender!=''">
AND gender = #{gender}
</if>
<if test="username!=null and gender!=''">
AND username LIKE '%${username}%'
</if>
</where>
</select>
**
sql片段
没有定义sql片段之前
<select id="findUserById" parameterType="int" resultType="com.liuyanzhao.mybatis.po.User">
SELECT id,username,gender,birthday,address FROM user WHERE id=#{value}
</select>
定义和使用sql片段
<!--定义sql片段-->
<sql id="user_table_all_columns">
id,username,gender,birthday,address
</sql>
<!--查询用户-->
<select id="findUserById" parameterType="int" resultType="com.liuyanzhao.mybatis.po.User">
SELECT
<include refid="user_table_all_columns"/>
FROM user WHERE id=#{value}
</select>