mybaits实现oracle批量新增数据,回填主键

项目有需求,百度了很久,反正他们说的方法,我都没成功,我也不知道是不是我写代码的姿势不正确,没办法只能自己想法子了

我们这个项目用到了通过Mapper,通用Mapper里通过OracleProvider 实现批量插入,好像可以通过KeySql注解可以自动生成主键,

生成的sql里有这个

<bind name="country_idGenIdBind"  value="@tk.mybatis.mapper.genid.GenIdUtil@genId(record, 'countryId', @tk.mybatis.mapper.additional.insertlist.UUIdGenId@class, 'demo_country', 'country_id')"/>

本想想使用通过Mapper的,但是KeySql是通过Mapper的类,而我的实体类是放在api的模块里的,为了保持api模块里代码的纯净,不想使用它的方法

虽然用不了他们的代码,但是可以用他的方法,自己写sql,在forEach里加上bind标签,再自定义类实现属性注入,代码如下:

<foreach collection="list" item="item" open="(" close=")" separator="union">
    <bind name="build_idGenIdBind"  value="@com.xx.mybaits.Abc@a(item, 'field','SEQ_XX')"/>
    select
    #{item.field} as field
</foreach>

Abc的实现方法

 /**
     * @param target   传输对象
     * @param property 需要设置的属性名
     * @param seqName  生成id的序列名
     */
    public static void generateId(Object target, String property, String seqName) throws Exception {
        if (StringUtils.isBlank(seqName)) {
            throw new Exception("序列名不可为空!");
        }
        if (target != null) {
            Field field = FieldUtils.getDeclaredField(target.getClass(), property, true);
            Object fieldValue = field.get(target);
            if (fieldValue == null) {
                SequenceMapper sequenceMapper = SpringContext.getBean(SequenceMapper.class);
                Long nextSeq = sequenceMapper.getNextSeq(seqName);
                Class<?> fieldType = field.getType();
                if (fieldType.equals(Integer.class)) {
                    field.set(target, Integer.parseInt(nextSeq.toString()));
                    return;
                }
                field.set(target, nextSeq);
            }
        }
    }

 这里需要注意的是,myBaits默认是开启一级缓存的,需要把一级缓存关闭,否则循环查询序列时,返回的值不变,通过分布式系统时,一级缓存也会导致问题

猜你喜欢

转载自www.cnblogs.com/jaxlove-it/p/11978761.html