MyBatis三(读写操作)

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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值