https://mybatis.org/mybatis-3/zh/index.html >Mybatis官方文档介绍
从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
纯Mybatis配置
使用MAVEN创建项目
pom.xml配置
<!--做单元测试需要的 junit-->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
<!--MySQL Connector/J连接包-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
配置Maven静态资源过滤问题
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
创建User类
public class User {
private int id ;
private String name ;
private int age;
public int getId() {
return id;}
public void setId(int id) {
this.id = id;}
public String getName() {
return name;}
public void setName(String name) {
this.name = name;}
public int getAge() {
return age;}
public void setAge(int age) {
this.age = age;}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
创建mapper接口
这次主要是跟数据库打交道,所以不写service层。只写mapper来做演示
在里面写一个查询所有的方法
public interface UserMapper {
// 从数据库查询所有,封装成List然后返回到前台
public List<User> getUserList();
}
创建mapper.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="com.fullstack.mapper.UserMapper">
<resultMap type="User" id="userResultMap">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
</resultMap>
<select id="getUserList" resultMap="userResultMap">
select * from user ;
</select>
<select id="getUserInfo" resultType="User">
select * from user where id = #{id} ;
</select>
</mapper>
创建mybatis配置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>
<!--别名-->
<typeAliases>
<package name="com.fullstack.pojo"/>
</typeAliases>
<!--environments 环境,mybatis运行在什么样的环境中-->
<environments default="development">
<environment id="development"