在dao包下两个文件:
(1)StudentDao接口:(定义了两个方法)
selectStudents方法表示查询
insertStudent表示插入若干行记录
public interface StudentDao
{
List selectStudents();
int insertStudent(Student student);
}
(2)StudentDao.xml文件:在接口对应的xml文件中,上面的两个方法每个方法对应一个标签
selectStudents标签对应selectStudents方法
insertStudent标签对应insertStudent方法
insert into student values(#{id},#{name},#{email},#{age})
(3)utils包里面有工具类
public class MyBatisUtils
{
private static SqlSessionFactory factory=null;
static
{
try {
InputStream in= Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession()
{
SqlSession sqlSession=null;
if(factory!=null)
{
sqlSession=factory.openSession();//非自动提交事务,想要自动提交事务就传入一个true
}
return sqlSession;
}
}
调用这个类的getSqlSession方法就能得到一个SqlSession对象sqlSession 即代码:SqlSession sqlSession= MyBatisUtils.getSqlSession();就能获得
其实就等价于:
//读取主配置文件
InputStream in= Resources.getResourceAsStream("mybatis.xml");
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//创建SqlSessionFactory对象
SqlSessionFactory factory=builder.build(in);
//获取SqlSession对象,从 SqlSessionFactory中获取SqlSession
SqlSession sqlSession=factory.openSession(true);
(4)有了SqlSession对象sqlSession之后,想要调用StudentDao中的两个方法selectStudents和insertStudents方法就很简单了,只需要几行代码即可,dao.接口中的方法()即可,
比如dao.selectStudent(),或者是dao.insertStudent()
1.调用selectStudents方法
SqlSession sqlSession= MyBatisUtils.getSqlSession(); StudentDao dao= sqlSession.getMapper(StudentDao.class); Liststudents=dao.selectStudents(); for(Student stu:students) { System.out.println("学生="+stu); }
2.调用insertStudents方法:
SqlSession sqlSession= MyBatisUtils.getSqlSession();
StudentDao dao= sqlSession.getMapper(StudentDao.class);
Student student=new Student();
student.setId(1007);
student.setName("李飞飞");
student.setEmail("lifeifei@163.com");
student.setAge(28);
int nums=dao.insertStudent(student);
sqlSession.commit();
System.out.println("添加对象的数量:"+nums);



