- 1、本文档共14页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
iBatis学习笔记02
ibatis 3 学习笔记 2
博客分类:
Ibtais
iBATISXMLJDBC配置管理SQL
上篇简单调试了一个实例,现在仔细看看ibatis 3 user guide上的内容,接下来的几篇准备整理user guide上的内容,最后通过一个综合的例子来实践。关于实体映射文件中namespace,以前的版本是可选的内容,现在被用来与接口绑定,也就是说把接口的实现转移到xml文件中来了,以后的维护会相当的方便。第一篇的根据id查询学生的例子中,稍做修改:建立StudentDAO接口
Java代码
package cn.pf.ibatis.dao;
import java.util.List;
import cn.pf.ibatis.domain.Student;
/**
* StudentDAO接口
* @author pf
* @version 2010-3-16下午03:05:36
*/
public interface StudentDAO {
public Student queryStudentById(int id);
}
更改 student.xml中的mapper元素namespace属性test.java中调用改为
Java代码
Student student;
StudentDAO studentDAO = session.getMapper(StudentDAO.class);
try{
//student = (Student)session.selectOne(cn.pf.ibatis.domain.StudentMapper.selectStudent, 1);
student = studentDAO.queryStudentById(1);
}finally{
session.close();
}
System.out.println(student.toString());
生命周期SqlSessionFactoryBuilder:用于建立SqlSessionFactory的工具类,在创建 SqlSessionFactory以后无需再让它存在于应用程序中,文档上说它的生命周期最好在局部方法内,所以在代码中看到//根据资源文件内容建立session工厂SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);没用引用指向 SqlSessionFactoryBuilder,会被gc回收。SqlSessionFactory:一旦建立,SqlSessionFactory就应该存在于整个应用程序生命周期,因为根据资源文件建立SqlSessionFactory对象需要很大的开销,所以保留在整个应用的生命周期中,最佳实践中推荐使用spring等依赖注入的框架从而管理SqlSessionFactory的单例生命周期。SqlSession:每一个线程都应该有自己的SqlSession对象,SqlSession对象不是线程安全的所以不应该被共享,如果使用web框架,应该将SqlSession的生命周期看作HTTP Request的生命周期,在返回HTTP Response的时候关闭SqlSession
引用
SqlSession session = sqlSessionFactory.openSession();try { // do work} finally { session.close();}
Mapper Instances:Mapper Instances是绑定ibatis映射文件实现的接口,Mapper Instances的生命周期应该与SqlSession一样,但是Mapper Instances最好在一个方法中被创建,在方法结束时被销毁。
Java代码
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
// do work
} finally {
session.close();
}
配置文件配置文件的层次结构如下:? configuration o properties o settings o typeAliases
文档评论(0)