国王陛下万万岁

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

MyBatis入门1创建了一个Dao接口类和一个mybatis的xml格式mapper文件,以及mybatis的主配置文件。

在运行测试类的时候,发现没有Dao接口类也能查询数据库,这是因为没有使用以下maybatis的方法去获取mapper。

sqlSession.getMapper();

 

总之,这个Dao接口没有起到作用,可以删除。

下面代码模拟mybatis使用实现类调用dao接口的方法去查询数据库

com/oxygen/dao/impl/StudentDaoImpl.java

复制代码
package com.oxygen.dao.impl;

import com.oxygen.dao.StudentDao;
import com.oxygen.entity.Student;
import com.oxygen.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> selectStudentsAll() {
        SqlSession sqlSession= MybatisUtil.getSqlSession();
        String sqlId="com.oxygen.dao.StudentDao.selectStudentsAll";
        List<Student> result=sqlSession.selectList(sqlId);
        result.forEach(System.out::println);
        sqlSession.close();
        return result;
    }

    @Override
    public int insertStudent(Student student) {
        return 0;
    }
}
复制代码

 

测试类

src/test/java/TestStudentImpl.java

复制代码
import com.oxygen.dao.StudentDao;
import com.oxygen.dao.impl.StudentDaoImpl;
import com.oxygen.entity.Student;
import org.junit.Test;

import java.util.List;

public class TestStudentImpl {

    @Test
    public void testStudent(){
        StudentDao dao=new StudentDaoImpl();
        List<Student> students=dao.selectStudentsAll();
        for(Student stu:students){
            System.out.println("stu->"+stu);
        }
    }
}
复制代码

 

posted on   国王陛下万万岁  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
 
点击右上角即可分享
微信分享提示