MyBatis的使用步骤及配置
1.导入mybatis的jar包:mybatis-x.x.x.jar
2.使用XML配置mybatis,创建SqlSessionFactory
XML配置文件的名称通常为mybatis-config.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="oracle.jdbc.driver.OracleDriver"/>
- <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
- <property name="username" value="username"/>
- <property name="password" value="password"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="org/mybatis/example/BlogMapper.xml"/>
- <!-- <package name="com.example.manager.mapper"/> -->
- </mappers>
- </configuration>
该配置文件使用文件流的形式读入,通过mybatis的工具类Resources加载资源文件:
- String resource = "org/mybatis/example/mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3.从 SqlSessionFactory 中获取 SqlSession
- SqlSession session = sqlSessionFactory.openSession();
- try {
- Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
- } finally {
- session.close();
- }
4.最简单的使用方法:mybatis-config.xml + mapper.xml + test.java
mybatis-config.xml配置
- <mapper resource="org/mybatis/example/BlogMapper.xml"/>
resource的路径通常为包路径,众多mapper.xml通常被放置在一个包下
mapper.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="org.mybatis.example.BlogMapper">
- <select id="selectBlog" resultType="Map">
- select * from Blog where id = #{id}
- </select>
- </mapper>
- namespace:命名空间,映射查询的关键参数
id:调用方法定义
resultType:结果集对象类型(Map可以被HashMap接收,然后转为json,也可以自定义类型)
传递参数:参数替换分两种:#{id} => 预处理语句的? || '${id}' => 直接替换为变量- test.java
- public static void main(String[] args) {
- SqlSessionFactory sqlSessionFactory;
- SqlSession session = null;
- try {
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- session = sqlSessionFactory.openSession();
- HashMap<String,String> result = session.selectOne("selectBlog", 110);
- System.out.println("Result: "+result);
- } catch (Exception ex) {
- ex.printStackTrace();
- } finally {
- if(session != null){
- session.close();
- }
- }
- }
session.selectOne是session自带方法(selectList可以获取多条数据),传入的第一个字符串就是之前定义的id,第二个参数是传入的参数(多个参数可以使用一个HashMap来传参)。
5.简单抽象方法:mybatis-config.xml + mapper.xml + interface.java + test.java
mybatis-config.xml
- <package name="com.mybatis.manager.mapper"/>
mapper.xml
- <mapper namespace="com.mybatis.manager.mapper.ReleaseDTOMapper">
- <select id="getReleaseNote" parameterType="map" resultType="map">
- SELECT rn.* FROM GPCM_RELEASE_NOTE rn where rn.state = #{STATE} and rn.upgrade_id = #{UPGRADE_ID}
- </select>
- <select id="getUpgradeNote" parameterType="map" resultType="map">
- SELECT un.* FROM GPCM_UPGRADE_NOTE un
- </select>
- </mapper>
interface.java
- public interface ReleaseDTOMapper {
- public HashMap<String,String> getReleaseNote(HashMap<String,String> param);
- public ArrayList<HashMap<String,String>> getUpgradeNote();
- }
test.java
- public static void main(String[] args) {
- SqlSessionFactory sqlSessionFactory;
- SqlSession session = null;
- try {
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- session = sqlSessionFactory.openSession();
- ReleaseDTOMapper mapper = session.getMapper(ReleaseDTOMapper.class);
- HashMap<String,String> param = new HashMap<String,String>();
- param.put("STATE", "N");
- param.put("UPGRADE_ID","2");
- HashMap<String,String> result = mapper.getReleaseNote(param);
- System.out.println("Result: "+result);
- List<HashMap<String,String>> rs = mapper.getUpgradeNote();
- for(HashMap<String,String> r : rs){
- System.out.println("Result: "+r);
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- } finally {
- if(session != null){
- session.close();
- }
- }
- }
6.通用方法:使用自定义数据类型映射参数和结果集
mapper.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.mybatis.manager.mapper.ReleaseDTOMapper">
- <resultMap id="BaseResultMap" type="com.mybatis.manager.persist.ReleaseNoteDTO" >
- <result column="RELEASE_ID" property="releaseId" jdbcType="INTEGER" />
- <result column="RELEASE_NAME" property="releaseName" jdbcType="VARCHAR" />
- <result column="RELEASE_DESC" property="releaseDesc" jdbcType="VARCHAR" />
- <result column="UPGRADE_ID" property="upgradeId" jdbcType="INTEGER" />
- <result column="STATE" property="state" jdbcType="VARCHAR" />
- <result column="CREATE_DATE" property="createDate" jdbcType="TIMESTAMP" />
- <result column="MOD_DATE" property="modDate" jdbcType="TIMESTAMP" />
- <result column="UPGRADE_DATE" property="upgradeDate" jdbcType="TIMESTAMP" />
- </resultMap>
- <select id="getReleaseNote" parameterType="com.mybatis.manager.persist.ReleaseNoteDTO" resultMap="BaseResultMap">
- SELECT rn.* FROM GPCM_RELEASE_NOTE rn where rn.state = #{state,jdbcType=VARCHAR} and rn.upgrade_id = #{upgradeId,jdbcType=INTEGER}
- </select>
- </mapper>
注意resultType -> resultMap,列与java对象的参数必需要对应,否则获取的结果就是null。
传入的参数为一个是可以定义parameterType="java.lang.Integer",多个参数必需合为一个对象传输,如Map或自定义Dto。
可以使用多表查询,将结果集传入一个自定义Dto中,结果集绑定如下:
- <resultMap id = "Upgrade" type="com.mybatis.manager.persist.UpgradeNoteDto">
- <result column="UPGRADE_ID" property="upgradeId" jdbcType="INTEGER" />
- <result column="UPGRADE_NAME" property="upgradeName" jdbcType="VARCHAR" />
- </resultMap>
- <resultMap id="BaseResultMap" type="com.mybatis.manager.persist.ReleaseNoteDto" >
- <result column="RELEASE_ID" property="releaseId" jdbcType="INTEGER" />
- <result column="RELEASE_NAME" property="releaseName" jdbcType="VARCHAR" />
- <result column="RELEASE_DESC" property="releaseDesc" jdbcType="VARCHAR" />
- <association property = "upgrade" javaType="com.mybatis.manager.persist.UpgradeNoteDto" resultMap = "Upgrade"/>
- </resultMap>
property = "upgrade"在Dto中定义为
- private UpgradeNoteDto upgrade;
ReleaseNoteDTO.java 自定义数据模型
- public class ReleaseNoteDTO {
- private Integer releaseId;
- private String releaseName;
- private String releaseDesc;
- private Integer upgradeId;
- private String state;
- private Date createDate;
- private Date modDate;
- private Date upgradeDate;
- /*******************
- *GETTER/SETTER
- *******************/
- }
interface.java
- public interface ReleaseNoteDtoMapper {
- public ReleaseNoteDto getReleaseNote(ReleaseNoteDto param);
- }
test.java
- ReleaseNoteDTO param = new ReleaseNoteDTO();
- param.setState("N");
- param.setUpgradeId(2);
- ReleaseNoteDTO result = mapper.getReleaseNote(param);
- System.out.println("Result: "+result.getReleaseDesc());
7.基本应用的结构参考
原文出处:https://www.cnblogs.com/windyofsky/p/5230570.html
MyBatis的使用步骤及配置的更多相关文章
- MyBatis框架基于XML的配置
什么是MyBatis? 答:它是一个持久层框架 说的太简单了吗?那让我们来看一下官方的文档描述: MyBatis有什么作用呢? 1.持久层的零实现 2.可以自动将数据封装到对象里面不需要手工编写映射的 ...
- 深入浅出Mybatis系列(四)---配置详解之typeAliases别名(mybatis源码篇)
上篇文章<深入浅出Mybatis系列(三)---配置详解之properties与environments(mybatis源码篇)> 介绍了properties与environments, ...
- 深入浅出Mybatis系列(三)---配置详解之properties与environments(mybatis源码篇)
上篇文章<深入浅出Mybatis系列(二)---配置简介(mybatis源码篇)>我们通过对mybatis源码的简单分析,可看出,在mybatis配置文件中,在configuration根 ...
- 深入浅出Mybatis系列(二)---配置简介(mybatis源码篇)
上篇文章<深入浅出Mybatis系列(一)---Mybatis入门>, 写了一个Demo简单体现了一下Mybatis的流程.本次,将简单介绍一下Mybatis的配置文件: 上次例子中,我们 ...
- Mybatis 3.3.0 Log4j配置
最近做一个SSM学习项目,配置log4j,mybatis用下面的方式配置,不管用,打印不出执行的SQL语句. log4j.logger.java.sql.Connection=DEBUGlog4j.l ...
- MyBatis Generator自动生成的配置及使用
注意:文件名不能有中文字符,不然不能自动生成 找到MyBatis Generator.rar\MyBatis Generator\eclipse里的features和plugins文件,把这两个文件复 ...
- myBatis 基础测试 表关联关系配置 集合 测试
myBatis 基础测试 表关联关系配置 集合 测试 测试myelipse项目源码 sql 下载 http://download.csdn.net/detail/liangrui1988/599388 ...
- Spring-MVC开发步骤(入门配置)
Spring-MVC开发步骤(入门配置) Step1.导包 spring-webmvc Step2.添加spring配置文件 Step3.配置DispatcherServlet 在web.xml中: ...
- spring+mybatis的多源数据库配置实战
前言: 关于spring+mybatis的多源数据库配置, 其实是个老生常谈的事情. 网上的方案出奇的一致, 都是借助AbstractRoutingDataSource进行动态数据源的切换. 这边再无 ...
随机推荐
- [转载]TSO、UFO、GSO、LRO、GRO和RSS介绍
TSO.UFO.GSO.LRO.GRO和RSS介绍 ethtool -k < 网络接口>,ethtool --show-offload < 网络接口>,或者可以看到很多网络接口 ...
- Linux驱动 - SPI驱动 之四 SPI数据传输的队列化
我们知道,SPI数据传输可以有两种方式:同步方式和异步方式.所谓同步方式是指数据传输的发起者必须等待本次传输的结束,期间不能做其它事情,用代码来解释就是,调用传输的函数后,直到数据传输完成,函数才会返 ...
- NB-LOT 科普
最全科普!你一定要了解的NB-IoT 2017-06-19 21:04物联网/操作系统/科普 工信部下发通知推动150万NB-IoT基站落地.NB-IoT汹涌而来.很多网友要求雇佣军科普一篇NB-Io ...
- XXXAction-validation.xml文件中报错:Referenced file Contains errors
我们需要引用与验证器配置相关的dtd文件,这个文件可以在xwork-core-2.3.1.2.jar下找到(xwork-validator-1.0.3.dtd) 网上有很多处理办法,如下所示: 1.直 ...
- rails的respond to format
Here are all the default Rails Mime Types: "*/*" => :all "text/plain" => : ...
- ios下编译opencv
如果想要在ios下编译opencv 需要安装Cmake 这里通过homebrew 来安装cmake ios下打开终端然后先安装 homebrew :(mac 下自带ruby) ruby -e &quo ...
- python之数据库的操作(课前准备)
数据库(Database)是按照数据结构来组织.存储和管理数据的仓库. 上面的就是数据库的定义. 何为数据库,简单的来说,就是我们的大型数据的存放地点. 而我们学习的呢就是数据库的访问层的制作. 何为 ...
- 第二天:tomcat体系结构和第一个Servlet
1. 打war包 2. Tomcat体系再说明: 问题:如何去配置默认主机??? 3.tomcat和servlet在网络中的位置 4. servlet快速入门案例 1).开发s ...
- Ajax入门(一)从0开始到一次成功的GET请求
什么是服务器 网页浏览过程分析 一个完整的HTTP请求过程,通常有下面7个步骤 建立TCP连接 Web浏览器向Web服务器发送请求命令 Web浏览器发送请求头信息 Web服务器- 应答 Web服务器- ...
- 【总结整理】openlayer
实时路况 http://www.cnblogs.com/gisvip/archive/2012/11/24/2787141.html