MyBatis简介
2017-02-23 16:55
169 查看
Mybatis 简介
MyBatis 的安装使用
使用Maven引入,把依赖放入pom.xml文件中<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>x.x.x</version> </dependency>
获取SqlSessionFactory,每个基于MyBatis的应用都是以一个SqlSessionFactory的实例为中心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。
SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。
String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
XML配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
XML 头部的声明,用来验证 XML 文档正确性
environment 元素体中包含了事务管理和连接池的配置
mappers 元素则是包含一组 mapper 映射器(这些 mapper 的 XML 文件包含了 SQL 代码和映射定义信息)
在java程序中构建SqlSessionFactory
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource(); TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration configuration = new Configuration(environment); configuration.addMapper(BlogMapper.class); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
获取 SqlSession
SqlSession session = sqlSessionFactory.openSession(); try { Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101); } finally { session.close(); } 或者 SqlSession session = sqlSessionFactory.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101); } finally { session.close(); }
生命周期
SqlSessionFactoryBuilder : 方法内
SqlSessionFactory : 整个应用
SqlSession : 每个线程,如每次收到一个http请求,打开,返回一个响应,关闭
Mapper (映射器实例): 方法
相关文章推荐
- MyBatis之简介(0)
- JAVAWEB开发之SpringMVC详解(一)——SpringMVC的框架原理、架构简介、与mybatis整合和注解方式的使用、
- 【Spring+MyBatis】-----简介
- Mybatis 简介与原理
- Druid简介(Spring Boot + Mybatis + Druid数据源【自己定制】)
- 【持久化框架】Mybatis简介与原理
- mybatis简介
- mybatis学习 一、MyBatis简介与配置MyBatis+Spring+MySql
- 分布式框架简介SSM组合+ springmvc+mybatis+shiro+restful+bootstrap
- 博为峰JavaEE技术文章 ——MyBatis Hibernate 简介
- MyBatis学习之一:MyBatis简介与配置MyBatis+Spring+MySql
- MyBatis之ResultMap简介
- mybatis 几种实现模糊查询的方法简介
- MyBatis简介与配置MyBatis+Spring+MySql
- 深入浅出Mybatis系列(二)---配置简介(mybatis源码篇)
- 一、MyBatis简介与配置MyBatis+Spring+MySql
- Shiro简介——跟我学习springmvc shiro mybatis
- MyBatis 简介
- mybatis的简介
- MyBatis 简介