mybaits根据已有数据库数量判断是否插入

来源:互联网 发布:java file类 编辑:程序博客网 时间:2024/06/01 11:06

目前有这一需求,在数据库按照某条件检索如果数量大于一个数,默认就不插入,返回影响数据条目数应该为0.。

这样在插入时,参数一共两个一个是要插入的实体类另一个就是要判断的数量,这里mybaits的参数类型就要用map来进行传入,同时根据key值来直接获取。针对在插入时判断,就要采用insert into 数据表 select 具体值 from DUAL where 条件,这种语句来实现。

这里mapper.xml代码如下:

<insert id="insertSealUnderCount" parameterType="java.util.Map">
        insert into tss(seal_id, seal_type)
        select #{seal.sealId}, #{seal.sealType}  from DUAL  where (select count(*) from tss where status=1 or status=2) &lt; #{count}
    </insert>

对应dao层如下:

public int insertSealUnderCount(Map<String, Object> map);

测试类如下:

import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.aisino.dao.SealDao;
import com.aisino.data.Response;
import com.aisino.entity.Seal;
import com.aisino.service.DeviceAuthService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:conf/spring.xml","classpath:conf/spring-mybatis.xml","classpath:conf/activemq.xml"})
public class SealTest {
@Autowired
private DeviceAuthService deviceservice;
@Autowired
private SealDao sealdao;

@Test
public void test2(){
    Map<String,Object> map=new HashMap<String,Object>();
    Seal seal=new Seal();
    seal.setSealId("12345678");
    seal.setSealType(1);
    map.put("seal", seal);
    map.put("count", 10);
//    sealdao.insertSeal(seal);
    int i=sealdao.insertSealUnderCount(map);
    System.out.println(i);
}
}

执行结果:

数据库表有些字段出于隐私这里省略,大致整体思路就是这样,这里记录一下。

阅读全文
0 0
原创粉丝点击