MyBatis 入门开发 —-输入,输出参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis 入门开发 —-输入,输出参数相关的知识,希望对你有一定的参考价值。
第一: parameterType传入参数传递简单数据类型
<select id="findUserById" parameterType="int" resultType="cn.fy.domain.User">
SELECT id,username,birthday,sex,address FROM USER WHERE id = #{id}
</select>
传递pojo对象
<!—传递pojo对象综合查询用户信息 -->
user 使用了别名.
<select id="findUserByUser" parameterType="user" resultType="user">
select * from user where id=#{id} and username like ‘%${username}%‘
</select>
#{id} : 使用 user中的id
${username}:使用user中的username.
// 如果参数类型user 中有属性 order 类
<select id="findUserByUser" parameterType="user" resultType="user">
select * from user where id=#{order.id} and username like ‘%${username}%‘
</select>
mybatis可以通过ognl 表达式: #{属性.属性.属性}
传递hashmap
map综合查询用户信息 -->
<select id="findUserByHashmap" parameterType="hashmap" resultType="user">
select * from user where id=#{id} and username like ‘%${username}%‘
</select>
@Test
public void findUserByHashmap() {
SqlSession session = MyBatisUtil.getSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
//构造查询条件Hashmap对象
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("id", 1);
map.put("username", "张");
//传递Hashmap对象查询用户列表
List<User>list = userMapper.findUserByHashmap(map);
//关闭session
session.close();
}
select * from user where id=? and username like ‘%管理员%‘
第二: resultType(输出类型)输出简单类型
Public void testFindUserCount() throws Exception{ //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口实例 UserMapper userMapper = session.getMapper(UserMapper.class); User user = new User(); user.setUsername("管理员"); //传递Hashmap对象查询用户列表 int count = userMapper.findUserCount(user); //关闭session session.close(); } 输出简单类型 Public void testFindUserById() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获限mapper接口实例 UserMapper userMapper = session.getMapper(UserMapper.class); //通过mapper接口调用statement User user = userMapper.findUserById(1); System.out.println(user); //关闭session session.close(); } 输出pojo列表 @Test public void dimFind() { SqlSession session = MyBatisUtil.getSession(); List以上是关于MyBatis 入门开发 —-输入,输出参数的主要内容,如果未能解决你的问题,请参考以下文章