# 删除mybatis_demo数据库
drop database if exists mybatis_demo;
# 创建mybatis_demo数据库
create database mybatis_demo;
# 使用mybatis_demo数据库
use mybatis_demo;
# 创建account表Proxy Pattern
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);
select单条数据
代码实现
在entity包下创建User实体类:User.java
package entity;
public class User {
private Integer id;
private String username;
private Integer age;
private Integer score;
// 省略getter&setter方法
// 省略toString方法
}
在dao包下创建User模块Dao层:UserDao.java
package dao;
public interface UserDao {
/**
* 通过用户id查询用户信息
*
* @param id
* @return
*/
User selectUserById(Integer id);
}
在mybatis-config.xml配置文件中添加上对应的mapper配置
在resources文件夹下新建dao包,并在其下新建User模块Dao层配置文件:UserDao.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="dao.UserDao">
<select id="selectUserById" resultType="entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
新建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();
// 得到 Dao
UserDao dao = session.getMapper(UserDao.class);
// 调用通过用户id查询用户信息的方法
User user = dao.selectUserById(1);
System.out.println(user);
// 关闭会话
session.close();
}
}
执行结果