1.创建一个web项目
2.导JAR包
分别有三类jar包:mybatis核心、mysql驱动、mybatis依赖
3.创建mybatis全局配置文件和映射配置文件
<?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>
<!-- default引用environment的id,当前所使用的环境 -->
<environments default="default">
<!-- 声明可以使用的环境 -->
<environment id="default">
<!-- 使用原生JDBC事务 -->
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="Qq991899783" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/run/mapper/UsersMapper.xml" />
</mappers>
</configuration>
<?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命名随意,这里用UserMapper全路径 -->
<mapper namespace="com.run.mapper.UsersMapper">
<select id="selectAll" resultType="com.run.pojo.Users">
select * from t_users
</select>
</mapper>
4.创建实体类
package com.run.pojo;
public class Users {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "Users [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
5.创建测试类
package com.run;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 com.run.pojo.Users;
public class App {
public static void main(String[] args) {
InputStream is = null;
try {
is = Resources.getResourceAsStream("mybatis.xml");
} catch (IOException e) {
e.printStackTrace();
}
// 使用工厂设计模式
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// 生产SqlSession
SqlSession session = factory.openSession();
List<Users> list = session.selectList("com.run.mapper.UsersMapper.selectAll");
for (Users user : list) {
System.out.println(user.toString());
}
session.close();
}
}