MyBatis—读写操作
一.insert
在MyBatis中编写Insert语句时使用< insert>,代码如下:
<mapper namespace="com.mybatis.demo">
<insert id="insert" parameterType ="com.mybatis.demo.User">
insert into tabuser (name, age) VALUES (#{name}, #{age});
<selectKey keyProperty = "id" resultType = "int" order = "AFTER">
select last_insert_id() as id
</selectKey>
</insert>
</mapper>
这里,parameteType可以根据需要将值作为string,int,float,double等任何类对象。如果数据库表使用IDENTITY,AUTO_INCREMENT或SERIAL列,或者已定义SEQUENCE / GENERATOR,则可以使用语句中的元素来使用或返回该数据库生成的值。
二.select
在MyBatis中编写select语句时使用< select>,代码如下:
<select id="getUser" resultType="com.mybatis.demo.User">
SELECT * FROM tabuser
<where>
<if test="_parameter != null">
Id = #{id}
</if>
</where>
</select>
三.update
在MyBatis中编写update语句时使用< update>,代码如下:
<update id="update" parameterType="com.mybatis.demo.User">
UPDATE tabuser SET NAME = #{name}
WHERE ID = #{id};
</update>
四.动态SQL
- if语句
SELECT * FROM tabuser
<if test = "name != null">
WHERE name LIKE #{name}
</if>
<if test = "id != null">
AND id LIKE #{id}
</if>
- choose语句
SELECT * FROM tabuser WHERE id != 0
<choose>
<when test = "name != null">
AND name LIKE #{name}
</when>
<when test = "phone != null">
AND phone LIKE #{phone}
</when>
</choose>
- where声明
在前面的if和choose示例,如果没有满足任何条件,则会生成这样的错误SQL语句:
SELECT * FROM tabuser WHERE
MyBatis的where则可以解决这一问题,如下:
SELECT * FROM tabuser
<where>
<if test = "name != null">
name LIKE #{name}
</if>
<if test = "id != null">
AND id LIKE #{id}
</if>
</where>
- foreach
foreach元素允许您指定一个集合并声明可以在元素主体内使用的项和索引变量,如下:
<select id="getUser" resultType="com.mybatis.demo.User">
SELECT * FROM tabuser where id in
<foreach item = "item" index = "index" collection = "list"
open = "(" separator = "," close = ")">
#{item}
</foreach>
</select>