在src目录下,创建包com.pojo,并在com.pojo包中创建Student类。添加如下代码:
package com.pojo;
public class Student {
private int stuId;
private String stuNum;
private String stuName;
private String stuGender;
private int stuAge;
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public String getStuNum() {
return stuNum;
}
public void setStuNum(String stuNum) {
this.stuNum = stuNum;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuGender() {
return stuGender;
}
public void setStuGender(String stuGender) {
this.stuGender = stuGender;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
@Override
public String toString() {
return "Student [stuId=" + stuId + ", stuNum=" + stuNum + ", stuName=" + stuName + ", stuGender=" + stuGender
+ ", stuAge=" + stuAge + "]";
}
}
3.创建DAO接口并定义操作方法
在src目录下,创建包com.dao,并在com.dao包中创建StudentDao类。添加如下代码:
package com.dao;
import com.pojo.Student;
public interface StudentDao {
public void insertStudent(Student student);
}
4.创建DAO接口的映射文件
①在src目录下,创建com.mapper文件夹。 ②在com.mapper中创建名为StudentMapper.xml的映射文件。 ③在映射文件中对DAO中定义的方法进行实现。
在StudentMapper.xml文件中添加如下代码:
5.将映射文件添加到主配置文件insert into tb_students(sid,stu_num,stu_name,stu_gender,stu_age) values(#{stuId},#{stuNum},#{stuName},#{stuGender},#{stuAge})
在mybatis-config.xml文件中添加如下代码:
6.添加单元测试的依赖(添加jar包)
junit-4.12.jar
hamcrest-core-1.3.RC2.jar
hamcrest-library-1.3.RC2.jar
如需下载其他版本的jar包,请点击:https://mvnrepository.com/,进入网站后直接在搜索框中搜索即可。
在src目录下,创建包com.test,并在com.test包中创建StudentDaoTest类。添加如下代码:
package com.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.dao.StudentDao;
import com.pojo.Student;
public class StudentDaoTest {
@Test
public void insertStudent() {
try {
Student stu=new Student();
stu.setStuId(1);
stu.setStuNum("10001");
stu.setStuName("张三");
stu.setStuGender("男");
stu.setStuAge(21);
//作为一个流加载mybatis配置文件
InputStream is=Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//会话工厂
SqlSessionFactory factory=builder.build(is);
//会话(连接)
SqlSession sqlSession=factory.openSession();
StudentDao studentDao=sqlSession.getMapper(StudentDao.class);
studentDao.insertStudent(stu);
// mybatis执行更新操作 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
8.单元测试
“Window”—“Show View”—“Outline”,在"Outline"窗口中,右击“insertStudent():void”,选择"Run As"—“JUnit Test”。如果在下图红色方框中的进度条为绿色,表示运行成功。
此时就可以看到数据库表tb_students中成功插入一条记录:



