list mybatis 接收 类型_Mybatis传入参数类型为List作为条件进行查询

表结构:

a418ead9ce32

表名称为constant

需求:

现在想查询type为2、3的所有数据(甚至想查询type为1,2,3,4,5....,100的所有数据)并且返回的值是Map(key为id,value为constant类)

如果采用一个一个传参的方式进行查询肯定是不行的,以下是通过Mybatis提供的foreach标签并配合in进行查询

Mapper:

select * from constant where type in

separator="," close=")">#{item}

DAO:

import java.util.List;

import java.util.Map;

import org.apache.ibatis.annotations.MapKey;

import org.springframework.stereotype.Repository;

@Repository

public interface ConstantDao {

/**

* 注释@MapKey表示表中那个字段作为Map的key

* @return

*/

@MapKey("id")

Map loadConstantByType(List type);

}

POJO实体类:

public class Constant {

private Long id;

private String key;

private String value;

private Integer type;

public String toString(){

StringBuffer s = new StringBuffer("Constant:{");

s.append("id:").append(this.id).append(",");

s.append("key:").append(this.key).append(",");

s.append("value:").append(this.value).append(",");

s.append("type:").append(this.type).append("}");

return s.toString();

}

public Constant() {

super();

// TODO Auto-generated constructor stub

}

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getKey() {

return key;

}

public void setKey(String key) {

this.key = key == null ? null : key.trim();

}

public String getValue() {

return value;

}

public void setValue(String value) {

this.value = value == null ? null : value.trim();

}

public Integer getType() {

return type;

}

public void setType(Integer type) {

this.type = type;

}

}

pojo中的实体类最好重写toString方法

junitTest:

import java.util.Arrays;

import java.util.List;

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;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mybatis.xml" })

public class MubatisMapTest {

@Autowired

private ConstantDao constantDao;

@Test

public void mapTest1() {

List typeList = Arrays.asList(2,3);

Map constantMap = constantDao.loadConstantByType(typeList);

System.out.println(constantMap);

}

}

最终测试结果:

a418ead9ce32

Paste_Image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值