MyBatis简介
MyBatis是一款优秀的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的工作。MyBatis通过简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
轻松传参基础
1. 参数类型
在MyBatis中,我们可以将参数传递给映射器(Mapper)的SQL语句,参数的类型主要有以下几种:
- 基本数据类型:int、long、float、double等。
- 包装类:Integer、Long、Float、Double等。
- 字符串类型:String。
- 对象类型:自定义对象。
- 集合类型:List、Set、Map等。
2. 参数传递方式
- XML映射文件:通过
<parameterType>指定参数类型,并在SQL语句中使用#{参数名}进行占位符传递。 - 注解:使用@Param注解在Mapper接口的方法参数上指定参数名。
实战案例分析
案例一:基本数据类型参数传递
假设我们有一个数据库表user,字段包括id、username和password。
XML映射文件:
<mapper namespace="com.example.mapper.UserMapper">
<select id="findUserById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
Mapper接口:
public interface UserMapper {
User findUserById(Integer id);
}
案例二:对象类型参数传递
假设我们有一个数据库表user,字段包括id、username和password。
XML映射文件:
<mapper namespace="com.example.mapper.UserMapper">
<select id="findUserByUsername" resultType="com.example.entity.User">
SELECT * FROM user WHERE username = #{user.username}
</select>
</mapper>
Mapper接口:
public interface UserMapper {
User findUserByUsername(User user);
}
案例三:集合类型参数传递
假设我们有一个数据库表user,字段包括id、username和password。
XML映射文件:
<mapper namespace="com.example.mapper.UserMapper">
<select id="findUsersByIds" resultType="com.example.entity.User">
SELECT * FROM user WHERE id IN
<foreach item="id" collection="list" open="(" separator="," close=")">
#{id}
</foreach>
</select>
</mapper>
Mapper接口:
public interface UserMapper {
List<User> findUsersByIds(List<Integer> list);
}
总结
通过以上案例,我们可以看到MyBatis在参数传递方面提供了多种方式,方便我们进行灵活的数据操作。在实际项目中,根据需求选择合适的参数传递方式,能够提高开发效率和代码可读性。
