mybatis扎谈

来源:互联网 发布:程序员被骗婚女方 编辑:程序博客网 时间:2024/05/22 08:31
 mybatis中返回自动生成的id

当有时我们插入一条数据时,由于id很可能是自动生成的,如果我们想要返回这条刚插入的id怎么办呢
在mysql数据中
我们可以在insert下添加一个selectKey用以指定返回的类型和值
<insert id="xxx" parammeterType="xxx">
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> 
              SELECT LAST_INSERT_ID() AS ID   
        </selectKey> 
insert into ...
</insert>
其中resultType表示返回的类型。ID就是返回的刚插入的ID

在oracle中类似selectKey如下
<selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id"> 
            SELECT LOGS_SEQ.nextval AS ID FROM DUAL 

        </selectKey>

二 mybatis中解决数据库与bean中字段不一样的方法
1 用as填充(此方法需要每个select都进行as,比较累赘)
如:select parent_id as parentId from user;

2 使用返回结果集
对字段与bean不一致的,进行resultMap,然后将id管理到select中
<resultMap type="Product" id="result_product">
        <result property="productTypeId" column="product_type_id"/>
        <result property="discountId" column="discount_id"/>
        <result property="entryDate" column="entry_date"/>
    </resultMap>
<select id="getProductById" resultMap="result_product" resultType="Product"parameterType="String">
       select *
       from product
       where id=#{id}
    </select>

三 mybatis之缓存
mybatis中默认没有使用缓存,如果要使用缓存,一种方法是在xxxMapper.xml文件中添加 <cache />,这样
对于当前表的所有操作都会进行缓存。
但是当我们添加更新或者删除一条数据时,我们不希望使用缓存,因为这时缓存中的数据并不是最新的,所以每当我们进行一次这样的操作时应该清除一下缓存,方法就是在相关的insert 或者 update delete中添加一句刷新缓存的属性  flushCache="true",这样在进行查找时就会直接从数据库查询而不是从缓存中查询,所以这样得来的数据才是最新的。

0 0