对象关系映射,Hibernate把ORM用的淋漓尽致。
要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可。
如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>x.x.x</version> </dependency>
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。
@Test public void test() throws IOException { //1、根据全局配置文件获取一个SqlSessionFactory对象; String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2、SqlSessionFactory;用它来创建sqlSession; //开启一次和数据库的会话;默认这个会话是非自动提交的; SqlSession openSession = sqlSessionFactory.openSession(true); //3、SqlSession;sql会话;相当于是connection;和数据库建立一次会话(连接) StudentDao studentDao = openSession.getMapper(StudentDao.class); Student student = new Student(null, "张三admin", 19, 98.98, new Date()); studentDao.saveStudent(student); //4、保存成功! // openSession.commit(); }
总结实现过程:
原文:http://www.cnblogs.com/limingxian537423/p/7173528.html