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.导入MySQL驱动包、MyBatis框架基础包并且添加MyBatis核心配置文件
(1)在mybatis-config.xml配置文件中添加上对应的mapper配置
<mappers>
<mapper class="mapper.UserMapper"/>
</mappers>
(2)新建mapper包,并在其下新建UserMapper.java类
package mapper;
public interface UserMapper {
/**
* 通过用户id查询用户名称
*
* @param id 用户id
* @return 用户名称
*/
String selectUsernameById(Integer id);
}
测试结果:
**3.在entity包下创建User实体类:User.java
package entity;
public class User {
private Integer id;
private String username;
private Integer age;
private Integer score;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
运行结果:
4.创建UserTest.java文件**
import entity.User;
import mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
@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);
// 调用XML的SQL
Integer age = mapper.selectUserAgeById(1);
System.out.println("age: " + age);
// 调用通过用户id查询用户信息的方法
User user = mapper.selectUserById(1);
System.out.println(user);
// 关闭会话
session.close();
}
}
运行结果: