什么是Mapper
在MyBatis工程搭建 中我们主要讲解的是 MyBatis 如何连接数据库,具体执行 SQL 语句使用的是 JDBC 方式
但在实际应用中是不会选择 JDBC 来执行 SQL 的,MyBatis 提供了 Mapper 作为 Java 方法和 SQL 语句之间的桥梁,来帮助我们更好地去使用 SQL
Java 接口方法与 SQL 语句以及 mapper 之间的关系如下图所示:
新建Maven项目名为“mybatis-mapper“,设置好Maven版本、配置文件以及Maven仓库
准备数据源
因为MyBatis是一个持久层框架,所以我们在使用之前需要执行如下SQL语句备好数据源
<select id="login" parameterType="person" resultMap="personResult">
select * from person where name=#{name} and password=#{password}
</select>
<select id="findAll" resultMap="noteResult">
select * from note
</select>
<insert id="add" parameterType="note">
insert into note(title,author,content) values(#{title},#{author},#{content})
</insert>
<delete id="delete" parameterType="java.lang.Integer">
delete from note where id=#{id}
</delete>
<select id="load" parameterType="java.lang.Integer" resultMap="noteResult">
select * from note where id=#{id}
</select>
<update id="update" parameterType="person">
update note set title=#{title},author=#{author},content=#{content} where id= #{id}
</update>
<select id="query" parameterType="note" resultMap="noteResult">
select * from note
<where>
<if test="id != null and id != ''">
and id like concat('%',#{id},'%')
</if>
<if test="title != null and title != ''">
and title like concat('%',#{title},'%')
</if>
<if test="author != null and author != ''">
and author like concat('%',#{author},'%')
</if>
<if test="content != null and content != ''">
and content like concat('%',#{content},'%')
</if>
</where>
</select>
注解方式使用Mapper
代码实现
要想使用MyBatis首先需要导入MySQL驱动包、MyBatis框架基础包并且添加MyBatis核心配置文件
在mybatis-config.xml配置文件中添加上对应的mapper配置
<!-- mapper配置 -->
<mappers>
<mapper class="mapper.UserMapper"/>
</mappers>
新建mapper包,并在其下新建UserMapper.java类
User模块Mapper层:UserMapper.java
package mapper;
public interface UserMapper {
/**
* 通过用户id查询用户名称
*
* @param id 用户id
* @return 用户名称
*/
String selectUsernameById(Integer id);
}
有了方法定义后,我们再通过注解为该方法添加上对应的SQL语句
select * from note where id=#{id}
User模块测试类:UserTest.java
@SuppressWarnings({"Duplicates"})
public class UserTest {
public static void main(String[] args) throws IOException, SQLException {
// 读取配置文件
InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
// 得到 SqlSessionFactory 核心类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// 开始一个 sql 会话
SqlSession session = sqlSessionFactory.openSession();
// 得到 mapper
UserMapper mapper = session.getMapper(UserMapper.class);
// 调用注解的SQL
String username = mapper.selectUsernameById(1);
System.out.println("username: " + username);
// 关闭会话
session.close();
}
}
测试结果
测试结果如下图所示: