Mybatis查询传递参数的三种方式
1.用注解的方式传递多个参数
2.构建map
3.构建查询条件类
需求:
根据姓名和年龄查询出符合条件数据
创建表:
create table t_user (
id number(6) primary key,
name varchar2(25),
age number(3));
insert into t_user values (1,'tom',18);
insert into t_user values(2,'jim',19);
insert into t_user values(3,'aaa',18);
insert into t_user values (4,'bbb',20);
创建User类
public class User {
private Integer id;
private String name;
private Integer age;
.......省略get,set.....
}
UserMapper
public interface UserMapper {
//1.注解方式
User query(@Param(value="name")String name,@Param(value="age")Integer age);
//2.构建map
User quertByMap(Map<String, Object> map);
//3.构建查询条件类,这里就用创建好的User代替
User queryByCondition(User user);
}
<?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" >
<mapper namespace="com.briup.dao.UserMapper" >
<select id="query" resultType="com.briup.domain.User">
select * from t_user where name=#{name} and age=#{age}
</select>
<select id="quertByMap" parameterType="map" resultType="com.briup.domain.User">
select * from t_user where name=#{name} and age=#{age}
</select>
<select id="queryByCondition" parameterType="com.briup.domain.User" resultType="com.briup.domain.User">
select * from t_user where name=#{name} and age=#{age}
</select>
</mapper>
public class MybatiesTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception {
String resource = "conf.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
// 测试
@Test
public void testQuery() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.query("aaa", 18);
System.out.println(user);
}
@Test
public void testQueryByMap() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "aaa");
map.put("age", 18);
User user = mapper.quertByMap(map);
System.out.println(user);
}
@Test
public void testQueryByCondition() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User conditon = new User();
conditon.setName("aaa");
conditon.setAge(18);
User user = mapper.queryByCondition(conditon);
System.out.println(user);
}
}