栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis2: 动态代理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis2: 动态代理

在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);     



List students=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);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/939186.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号