MyBatis实现Mapper配置并查询数据
1.准备数据源
# 删除mybatis_demo数据库
drop database if exists mybatis_demo;
# 创建mybatis_demo数据库
create database mybatis_demo;
# 使用mybatis_demo数据库
use mybatis_demo;
# 创建account表
create table user (
id int auto_increment primary key,
username varchar(20),
age int,
score int
);
# 新增数据
insert into user (id, username, age, score) values
(1,'peter', 18, 100), (2,'pedro', 24, 200),
(3,'jerry', 28, 500), (4,'mike', 12, 300),
(5,'tom', 27, 1000);
2.mapper配置
在mybatis-config.xml配置文件中添加上对应的mapper配置
<!-- mapper配置 -->
<mappers>
<mapper class="mapper.UserMapper"/>
</mappers>
3.新建mapper包,并在其下新建UserMapper.java类
package mapper;
public interface UserMapper {
/**
* 通过用户id查询用户名称
*
* @param id 用户id
* @return 用户名称
*/
String selectUsernameById(Integer id);
}
为该方法添加上对应的SQL语句
@Select("SELECT username FROM user WHERE id = #{id}")
4.新建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();
}
}
5.XML方式使用Mapper
在mybatis-config.xml配置文件中再新增一个方法selectUserAgeById,
/**
* 通过用户id查询用户年龄
*
* @param id 用户id
* @return 用户年龄
*/
Integer selectUserAgeById(Integer id);
6.在资源文件夹下新建mapper包,并在其下新建名为UserMapper的XML文件
<?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="mapper.UserMapper">
</mapper>