🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
mybatis基本使用步骤如下: <br/> **1. 封装工具类** ```java public class MybatisUtils { private static SqlSessionFactory sessionFactory = null; static { try { //读取核心配置文件并初始化 SqlSessionFactory InputStream ins = Resources.getResourceAsStream("mybatis-config.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(ins); } catch (IOException e) { e.printStackTrace(); } } /** * 连接数据库 */ public static SqlSession createConnetion() { return sessionFactory.openSession(true); } /** * 关闭与数据库的连接,每次调用createConnection()方法,都要调用该方法,以释放资源 */ public static void close(SqlSession sqlSession) { if (sqlSession != null) { sqlSession.close(); } } } ``` **2. 封装实体类** ```java @Data @NoArgsConstructor @AllArgsConstructor public class Student { private Integer id; private String name; private Date born; private String gender; } ``` **3. 封装dao层** (1)*`com.example.learn.mybatis.dao.StudentDao`* ```java public interface StudentDao { /** * 统计学生的人数. */ int counts(); } ``` (2)*`resources/mapper/StudentMapper.xml`* ```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"> <!-- namespace命名空间,对应dao层的接口 --> <mapper namespace="com.example.learn.mybatis.dao.StudentDao"> <!-- id: 对应StudentDao接口中的counts方法名 resultType: counts方法的返回值类型 --> <select id="counts" resultType="int"> select count(1) from student </select> </mapper> ``` **4. 测试** ```java public class StudentTest { private static SqlSession sqlSession = null; @Test public void counts() { try { //1. 连接数据库 sqlSession = MybatisUtils.createConnetion(); //2. 调用StudentDao接口中的counts方法 int counts = sqlSession.getMapper(StudentDao.class).counts(); System.out.println(counts); //5 } catch (Exception e) { e.printStackTrace(); } finally { //3. 关闭连接,释放资源 MybatisUtils.close(sqlSession); } } } ```