一,UserDAO 接口定义
首先,定义 UserDAO接口,包含 getList()方法,定义类型为List<User>:
package dao;import model.User;
import java.util.List;public interface UserDAO {List<User> getList();
}
二,User 映射器 XML 文件定义
创建一个MyBatis映射器XML文件,用于映射SQL查询到 UserDAO接口。常位于与接口相同的包结构中:
<?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"><!-- Result map to map the SQL result to User object --><resultMap id="userResultMap" type="model.User"><result property="id" column="id" /><result property="username" column="username" /><result property="email" column="email" /><result property="created_at" column="created_at" /></result>
//标签id="getList"对应接口的方法名字<!-- SQL Query to fetch all users --><select id="getList" resultMap="userResultMap">SELECT * FROM users</select></mapper>
三,配置 MyBatis
通常配置于mybatis-config.xml,确保映射器文件的路径
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/your_database"/><property name="username" value="root"/><property name="password" value="password"/></dataSource></environment></environments><mappers><mapper resource="dao/UserDAO.xml"/></mappers>
</configuration>
四,使用 DAO
在业务逻辑或控制器层,可以通过MyBatis的 SqlSession获取 UserDAO的实现,并调用 getList()
方法:
try (SqlSession session = sqlSessionFactory.openSession()) {
//实例是将 Java 方法映射到 SQL 查询的接口UserDAO userDAO = session.getMapper(UserDAO.class);
//用于从数据库中获取用户列表List<User> users = userDAO.getList();users.forEach(System.out::println);
}