参数怎么传入到sql语句中的呢?底层就是jdbc原始的做法,使用占位符的方式。
1. 简单参数
- dao代码:
/**
* 按id查询学生
*
*/
public Student selectStudentById(Integer id);
- StudentDao.xml代码
<!--parameterType="int 可以不写
mybatis内置类型:https://mybatis.org/mybatis-3/zh/configuration.html#typeAliases
#{id} 可以写成任意字符比如: #{dfsdf}
-->
<select id="selectStudentById" parameterType="int" resultType="com.yuhl.domain.Student">
select id,name,email,age from student where id =#{dfsdf}
</select>
-
parameterType=“int” 可以写也可以不写
可以参考:https://mybatis.org/mybatis-3/zh/configuration.html#typeAliases -
#{id}
#{id} 可以写成任意字符比如: #{dfsdf} 这个里面可以写任意字符、任意字符、任意字符记住了。
2. 测试通过:
@Test
public void test3() throws IOException {
SqlSession sqlsession = MybatisUtil.getSqlsession();
StudentDao studentDao = sqlsession.getMapper(StudentDao.class);
//StudentDao studentDao = new StudentDaoImpl();
Student student = studentDao.selectStudentById(1001);
System.out.println(student);
}
结果:
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 278934944.
==> Preparing: select id,name,email,age from student where id =?
==> Parameters: 1001(Integer)
<== Columns: id, name, email, age
<== Row: 1001, 张三, zhangsan@qq.com, 20
<== Total: 1
Student{id=1001, name='张三', email='zhangsan@qq.com', age=20}
3. 总结
简单参数的使用一定要掌握的。也很简单
下一篇:07-Mybatis参数的使用之二–多个参数的使用@Param https://blog.csdn.net/fsjwin/article/details/109669306