mybatis的selectKey和sql标签

一、xml方式

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <!--  
  如果使用xml的方式进行接口映射
  namespace的值必须是接口的全路径
   -->
 <mapper namespace="com.et.mybatis.selectKey.SqlKeyMapper">
    <insert id="insertArctic" parameterType="map">
          <selectKey keyProperty="id" order="BEFORE" resultType="int">
              <!-- 如果在oracle中 应该写的SQL语句是
                   select 序列.nextval from dual
                   select max(主键列)+1 from 对应表
               -->
              select max(id)+1 from arcticle
          </selectKey>
          insert into arcticle(id,title,content,userid)
          values(#{id},#{title},#{content},#{userid})
    </insert>
</mapper>

二、注解方式

package com.et.mybatis.selectKey.anno;

import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.SelectKey;

public interface SqlKeyAnnoMapper {
	/**
	 * statement表示要获取到的主键的sql语句
	 * keyProperty表示查询出来的值 应该被添加到参数中的键
	 *   就相同 map.put(keyProperty指定的名称,sql查询出的记过)
	 * resultType 指定 查询主键sql返回的类型
	 * before=true 表示在insert之前执行  
	 * @param map
	 */
	 @SelectKey(statement="select max(id)+1 from arcticle",
			 keyProperty="idssfdsdfsdf",
			 resultType=int.class,before=true)
	 @Insert("insert into arcticle(id,title,content,userid)"+
         " values(#{idssfdsdfsdf},#{title},#{content},#{userid})")
	 public void insertArcticAnno(Map map);
}


sql标签


<!--
     	 为了增强 sql的重用性  可以将通用的sql语句 通过id进行绑定
     	 在查询中如果需要使用这些通用的sql 可以直接通过id来引用
     	 <include refid="tsql"/> 
     -->
   <sql id="tsql">
   	  id,title,content
   </sql>
   <select id="queryArcticleMap" resultType="map">
     select <include refid="tsql"/> from arcticle where id=#{id}
  </select>
   <select id="queryAllArcticle" resultType="map">
     select <include refid="tsql"/> from arcticle 
  </select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值