一、mybatis环境搭建
mybatis核心配置文件, 文件名为 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置连接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<!-- 配置映射文件路径 -->
<mapper resource="mappers/userMapper.xml"/>
</mappers>
</configuration>
创建数据库
create database t_userDB;
use t_userDB;
create table t_user(
id int primary key auto_increment,
username varchar(30) not null ,
password varchar(30) not null
);
insert into t_user(username,password) values
('test01','test01'),('admin','admin');
select * from t_user;
根据数据库中的表字段,创建对应的实体类
public class User {
private Integer id;
private String username;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
}
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
}
创建mapper接口,mapper接口相当于之前的dao接口。只不过不创建实现类
public interface UserMapper {
int addUser();
}
创建映射文件
<?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">
<!-- namespace : 要操作的mapper接口 -->
<mapper namespace="com.xin.mybatis.mappers.UserMapper">
<!-- int addUser(); -->
<!-- id : 要和接口中的方法一致 -->
<insert id="addUser">
insert into t_user values(null,'张三','123456')
</insert>
</mapper>
测试添加用户方法
@Test
public void testAddUser() throws IOException {
// 1. 读取mybatis核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
// 2. 创建SpringSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// 3. 通过工厂类来创建 sqlSession对象
// openSession() 来创建sqlSession对象
SqlSession sqlSession = factory.openSession();
// 4.getMapper() 通过代理模式来创建实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.addUser();
// 5.提交sql语句
sqlSession.commit();
}
对应规则
1.表字段与实体类属性对应
2.mapper接口中的方法与映射文件中的id对应