以前都是通过写一个id 调用SqlSession方法,跟接口没什么关系,跟现在开发模式是不相符的,以下通过接口的实现类调用它的某个方法,执行sql语句:
创建StudentDaoImpl类,实现StudentDao接口:
package com.bjpowernode.dao.impl;
import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.domain.Student;
import com.bjpowernode.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
/*
以前都是通过写一个id 调用SqlSession方法,跟接口没什么关系,跟现在开发模式是不相符的,以下通过接口的实现类调用它的某个方法,执行sql语句
*/
public class StudentDaoImpl implements StudentDao {
@Override
public Student selectById(Integer id) {
//获取SqlSession对象
SqlSession sqlSession= MybatisUtil.getSqlSession();
String sqlId="com.bjpowernode.dao.StudentDao.selectById";
//调用SqlSession的方法
Student student = sqlSession.selectOne(sqlId,id);
//关闭sqlSession对象
sqlSession.close();
return student;
}
@Override
public List<Student> selectStudents() {
//获取SqlSession
SqlSession session= MybatisUtil.getSqlSession();
//2.指定sqlId
String sqlId="com.bjpowernode.dao.StudentDao.selectStudents";
//3.执行sqlSession的方法,执行sql语句
List<Student> students = session.selectList(sqlId);
//4.关闭SqlSession对象
session.close();
return students;
}
@Override
public int insertStudent(Student student) {
//获取SqlSession
SqlSession session= MybatisUtil.getSqlSession();
//2.指定sqlId
String sqlId="com.bjpowernode.dao.StudentDao.insertStudent";
//3.执行sqlSession的方法,执行sql语句
int rows = session.insert(sqlId, student);
session.commit();
System.out.println("insert的行数==="+rows);
//4.关闭SqlSession对象
session.close();
return rows;
}
}
测试类:MyTest2类:
package com.bjpowernode;
import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.dao.impl.StudentDaoImpl;
import com.bjpowernode.domain.Student;
import org.junit.Test;
import java.util.List;
public class MyTest2 {
//查询一个学生
@Test
public void testSelectOne(){
//接口类型 变量=new 接口实现类();
StudentDao dao=new StudentDaoImpl();
//使用dao的方法
Student student=dao.selectById(1001);
System.out.println("通过dao执行的方法,得到的对象="+student);
}
//查询所有
@Test
public void testSelectStudents(){
//接口类型 变量=new 接口实现类();
StudentDao dao=new StudentDaoImpl();
//使用dao的方法
List<Student> students=dao.selectStudents();
students.forEach(stu-> System.out.println("stu="+stu));
}
//添加学生
@Test
public void testInserttudents(){
//接口类型 变量=new 接口实现类();
StudentDao dao=new StudentDaoImpl();
//使用dao的方法
Student student=new Student();
student.setId(1009);
student.setName("周强");
student.setEmail("zhouqiang@.qq.com");
student.setAge(20);
dao.insertStudent(student);
}
}
第一个测试结果:
第二个测试结果:
第三个测试结果: