引入pom文件
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
先说一下最基础的
查询所有
<select id="方法名" resultType="返回的数据类型" >
查询单个
<select id="方法名" parameterType="参数类型" resultType="返回的数据类型" >
增删改
增删改不用写返回类型,固定为整型;输入参数为对象时,SQL语句点位符只需要写对象对应的属性名称
<insert id="方法名" parameterType="参数类型">
多个参数时
要在接口处使用@Param 绑定
使用map 或者对象时
一定要map.键名,或者对象点.属性名
使用resultMap时
方法返回结果的resultMap和resultType一定要分清
resultMap元素的顺序:id, result, association, collection顺序不可乱
属性名不一样时 使用 result
<mapper namespace="cn.kgc.mapper.UserMapper">
<!--结果映射,id:映射名称,文件内唯一,type:映射的实体类-->
<resultMap id="userMap" type="cn.kgc.entity.User">
<!--id-主键映射:property-属性名,column-列名-->
<id property="uid" column="uid"/>
<!--属性名与字段名的映射-->
<result property="gender" column="sex"/>
<!--其它能自动对应的可忽略不写-->
</resultMap>
当需要返回一个对象时使用association
通过一个id返回一个对象
<resultMap id="doctorMap" type="cn.kgc.entity.Doctor">
<id property="id" column="id"/>
// column 数据库查询的值 放入select指明的函数中执行,返回的结果填充至property对象
<association property="office"column="oid"select="cn.kgc.mapper.OfficeMapper.selectOfficeById"/>
</resultMap>
当需要返回多个对象时使用collection
通过一个id返回多个对象
<resultMap id="OfficeMap" type="cn.kgc.entity.Office">
<!-- collection 返回多个对象-->
<collection property="doctors" column="id" select="cn.kgc.mapper.DoctorMapper.selectDoctorByOid"/>
</resultMap>
动态sql
<select id="selectAllArticles" resultMap="articleMap">
select * from article
<where>
<if test="map.categoryId != null and map.categoryId != 0">
categoryId = #{map.categoryId}
</if>
<if test="map.title != null and map.categoryId != ''">
and title = #{map.title}
</if>
</where>
</select>
1.条件判断中使用and连接
2.当只有第二个判断成立时,sql语句的and 会自动省略
关闭下划线至驼峰的自动转换
.yml配置文件里面写
map-underscore-to-camel-case: false