mybatis反射机制
1.resultMap
对数据库及表的从新命名,也可以做返回参数对象
//type:对象名称(domain),id:新对象名称
<resultMap type="MArticle" id="MArticleResult">
//column:表名称,property:在java中的名称
<result property="id" column="id" />
<result property="ylTitle" column="yl_title" />
<association property="user" javaType="user">
<id property="id" column="u_id"/>
<result property="phone" column="u_phone"/>
</association>
</resultMap>
property:idea里的属性
column:数据库中的字段
association:类中还有一个类
2.sql
对SQL语句的封装
//id:命名
<sql id="selectMArticleVo">
//SQL语句
select id, yl_title from m_article
</sql>
3.select
3.1查询列表
<select id="selectMArticleList" parameterType="MArticle" resultMap="MArticleResult">
//就是相当于调用xml中的sql语句封装的方法
<include refid="selectMArticleVo"/>
<where>
//判断是否为null或“”,否则将数据库的信息提取出
<if test="img != null and img != ''"> and img = #{img}</if>
<if test="ylTitle != null and ylTitle != ''"> and yl_title = #{ylTitle}</if>
</where>
</select>
id:方法名,java代码中可以调用的方法
parameterType:接口中方法参数的类型, 类型的完全限定名或别名 ----传递进来的数据类型
resultMap:映射过来的的数据库结构名称
where:循环多次进行 注意:这个where是写在代码include中的,使用才能进行替换循环输出
类是:
3.2更具id查询
接口接收的数据是int,使用可以用long
<select id="selectMArticleById" parameterType="Long" resultMap="MArticleResult">
<include refid="selectMArticleVo"/>
where id = #{id}
</select>
这里的<include refid="selectMArticleVo"/>,指的是SQL封装(见二)的的最普通的查询
4.insert
<insert id="insertMArticle" parameterType="MArticle" useGeneratedKeys="true" keyProperty="id">
insert into m_article
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="ylTitle != null and ylTitle != ''">yl_title,</if>
<if test="flg != null">flg,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="ylTitle != null and ylTitle != ''">#{ylTitle},</if>
<if test="flg != null">#{flg},</if>
</trim>
</insert>
id与parameterType和之前的属性一样
4.1useGeneratedKeys
(仅适用于 insert 和 update)这会令 MyBatis 使用 JDBC 的getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的自动递增字段),默认值:false。
简单来说就是数据自增;
自增的字段为keyProperty的值(id)
4.2trim
trim 可用于剔除SQL语句中多余的 AND 关键字、逗号,或者给 SQL 语句前拼接 where、set 等后缀,可用于选择性插入、更新、删除或者条件查询等操作
格式:
例子:
<insert id="insertMArticle" parameterType="MArticle" useGeneratedKeys="true" keyProperty="id">
insert into m_article
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="ylTitle != null and ylTitle != ''">yl_title,</if>
<if test="flg != null">flg,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="ylTitle != null and ylTitle != ''">#{ylTitle},</if>
<if test="flg != null">#{flg},</if>
</trim>
</insert>
自己的笔记,更新中