1.导入mybatis的jar包mybatis-x.x.x.jar

2.使用XML配置mybatis,创建SqlSessionFactory

  XML配置文件的名称通常为mybatis-config.xml,内容基本格式如下:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <environments default="development">
  7. <environment id="development">
  8. <transactionManager type="JDBC"/>
  9. <dataSource type="POOLED">
  10. <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
  11. <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
  12. <property name="username" value="username"/>
  13. <property name="password" value="password"/>
  14. </dataSource>
  15. </environment>
  16. </environments>
  17. <mappers>
  18. <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  19. <!-- <package name="com.example.manager.mapper"/> -->
  20. </mappers>
  21. </configuration>

该配置文件使用文件流的形式读入,通过mybatis的工具类Resources加载资源文件:

  1. String resource = "org/mybatis/example/mybatis-config.xml";
  2. InputStream inputStream = Resources.getResourceAsStream(resource);
  3. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

3.从 SqlSessionFactory 中获取 SqlSession

  1. SqlSession session = sqlSessionFactory.openSession();
  2. try {
  3. Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
  4. } finally {
  5. session.close();
  6. }

4.最简单的使用方法:mybatis-config.xml + mapper.xml + test.java

mybatis-config.xml配置

  1. <mapper resource="org/mybatis/example/BlogMapper.xml"/>

resource的路径通常为包路径,众多mapper.xml通常被放置在一个包下

mapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="org.mybatis.example.BlogMapper">
  4. <select id="selectBlog" resultType="Map">
  5. select * from Blog where id = #{id}
  6. </select>
  7. </mapper>
  1. namespace:命名空间,映射查询的关键参数
    id:调用方法定义
    resultType:结果集对象类型(Map可以被HashMap接收,然后转为json,也可以自定义类型)
    传递参数:参数替换分两种:#{id} => 预处理语句的? || '${id}' => 直接替换为变量
  2.  
  3. test.java
  1. public static void main(String[] args) {
  2. SqlSessionFactory sqlSessionFactory;
  3. SqlSession session = null;
  4. try {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. session = sqlSessionFactory.openSession();
  9. HashMap<String,String> result = session.selectOne("selectBlog", 110);
  10. System.out.println("Result: "+result);
  11. } catch (Exception ex) {
  12. ex.printStackTrace();
  13. } finally {
  14. if(session != null){
  15. session.close();
  16. }
  17. }
  18. }

session.selectOne是session自带方法(selectList可以获取多条数据),传入的第一个字符串就是之前定义的id,第二个参数是传入的参数(多个参数可以使用一个HashMap来传参)。

5.简单抽象方法:mybatis-config.xml + mapper.xml + interface.java + test.java

mybatis-config.xml

  1. <package name="com.mybatis.manager.mapper"/>

mapper.xml

  1. <mapper namespace="com.mybatis.manager.mapper.ReleaseDTOMapper">
  2. <select id="getReleaseNote" parameterType="map" resultType="map">
  3. SELECT rn.* FROM GPCM_RELEASE_NOTE rn where rn.state = #{STATE} and rn.upgrade_id = #{UPGRADE_ID}
  4. </select>
  5. <select id="getUpgradeNote" parameterType="map" resultType="map">
  6. SELECT un.* FROM GPCM_UPGRADE_NOTE un
  7. </select>
  8. </mapper>

interface.java

  1. public interface ReleaseDTOMapper {
  2. public HashMap<String,String> getReleaseNote(HashMap<String,String> param);
  3.  
  4. public ArrayList<HashMap<String,String>> getUpgradeNote();
  5. }

test.java

  1. public static void main(String[] args) {
  2. SqlSessionFactory sqlSessionFactory;
  3. SqlSession session = null;
  4. try {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. session = sqlSessionFactory.openSession();
  9. ReleaseDTOMapper mapper = session.getMapper(ReleaseDTOMapper.class);
  10.  
  11. HashMap<String,String> param = new HashMap<String,String>();
  12. param.put("STATE", "N");
  13. param.put("UPGRADE_ID","2");
  14. HashMap<String,String> result = mapper.getReleaseNote(param);
  15. System.out.println("Result: "+result);
  16. List<HashMap<String,String>> rs = mapper.getUpgradeNote();
  17. for(HashMap<String,String> r : rs){
  18. System.out.println("Result: "+r);
  19. }
  20. } catch (Exception ex) {
  21. ex.printStackTrace();
  22. } finally {
  23. if(session != null){
  24. session.close();
  25. }
  26. }
  27. }

6.通用方法:使用自定义数据类型映射参数和结果集

mapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.mybatis.manager.mapper.ReleaseDTOMapper">
  4. <resultMap id="BaseResultMap" type="com.mybatis.manager.persist.ReleaseNoteDTO" >
  5. <result column="RELEASE_ID" property="releaseId" jdbcType="INTEGER" />
  6. <result column="RELEASE_NAME" property="releaseName" jdbcType="VARCHAR" />
  7. <result column="RELEASE_DESC" property="releaseDesc" jdbcType="VARCHAR" />
  8. <result column="UPGRADE_ID" property="upgradeId" jdbcType="INTEGER" />
  9. <result column="STATE" property="state" jdbcType="VARCHAR" />
  10. <result column="CREATE_DATE" property="createDate" jdbcType="TIMESTAMP" />
  11. <result column="MOD_DATE" property="modDate" jdbcType="TIMESTAMP" />
  12. <result column="UPGRADE_DATE" property="upgradeDate" jdbcType="TIMESTAMP" />
  13. </resultMap>
  14. <select id="getReleaseNote" parameterType="com.mybatis.manager.persist.ReleaseNoteDTO" resultMap="BaseResultMap">
  15. SELECT rn.* FROM GPCM_RELEASE_NOTE rn where rn.state = #{state,jdbcType=VARCHAR} and rn.upgrade_id = #{upgradeId,jdbcType=INTEGER}
  16. </select>
  17. </mapper>

注意resultType -> resultMap,列与java对象的参数必需要对应,否则获取的结果就是null。

  传入的参数为一个是可以定义parameterType="java.lang.Integer",多个参数必需合为一个对象传输,如Map或自定义Dto。

  可以使用多表查询,将结果集传入一个自定义Dto中,结果集绑定如下:

  1. <resultMap id = "Upgrade" type="com.mybatis.manager.persist.UpgradeNoteDto">
  2. <result column="UPGRADE_ID" property="upgradeId" jdbcType="INTEGER" />
  3. <result column="UPGRADE_NAME" property="upgradeName" jdbcType="VARCHAR" />
  4. </resultMap>
  5. <resultMap id="BaseResultMap" type="com.mybatis.manager.persist.ReleaseNoteDto" >
  6. <result column="RELEASE_ID" property="releaseId" jdbcType="INTEGER" />
  7. <result column="RELEASE_NAME" property="releaseName" jdbcType="VARCHAR" />
  8. <result column="RELEASE_DESC" property="releaseDesc" jdbcType="VARCHAR" />
  9. <association property = "upgrade" javaType="com.mybatis.manager.persist.UpgradeNoteDto" resultMap = "Upgrade"/>
  10. </resultMap>

property = "upgrade"在Dto中定义为

  1. private UpgradeNoteDto upgrade;

ReleaseNoteDTO.java 自定义数据模型

  1. public class ReleaseNoteDTO {
  2. private Integer releaseId;
  3. private String releaseName;
  4. private String releaseDesc;
  5. private Integer upgradeId;
  6. private String state;
  7. private Date createDate;
  8. private Date modDate;
  9. private Date upgradeDate;
  10. /*******************
  11. *GETTER/SETTER
  12. *******************/
  13. }

interface.java

  1. public interface ReleaseNoteDtoMapper {
  2. public ReleaseNoteDto getReleaseNote(ReleaseNoteDto param);
  3. }

test.java

  1. ReleaseNoteDTO param = new ReleaseNoteDTO();
  2. param.setState("N");
  3. param.setUpgradeId(2);
  4. ReleaseNoteDTO result = mapper.getReleaseNote(param);
  5. System.out.println("Result: "+result.getReleaseDesc());

7.基本应用的结构参考

原文出处:https://www.cnblogs.com/windyofsky/p/5230570.html

MyBatis的使用步骤及配置的更多相关文章

  1. MyBatis框架基于XML的配置

    什么是MyBatis? 答:它是一个持久层框架 说的太简单了吗?那让我们来看一下官方的文档描述: MyBatis有什么作用呢? 1.持久层的零实现 2.可以自动将数据封装到对象里面不需要手工编写映射的 ...

  2. 深入浅出Mybatis系列(四)---配置详解之typeAliases别名(mybatis源码篇)

    上篇文章<深入浅出Mybatis系列(三)---配置详解之properties与environments(mybatis源码篇)> 介绍了properties与environments, ...

  3. 深入浅出Mybatis系列(三)---配置详解之properties与environments(mybatis源码篇)

    上篇文章<深入浅出Mybatis系列(二)---配置简介(mybatis源码篇)>我们通过对mybatis源码的简单分析,可看出,在mybatis配置文件中,在configuration根 ...

  4. 深入浅出Mybatis系列(二)---配置简介(mybatis源码篇)

    上篇文章<深入浅出Mybatis系列(一)---Mybatis入门>, 写了一个Demo简单体现了一下Mybatis的流程.本次,将简单介绍一下Mybatis的配置文件: 上次例子中,我们 ...

  5. Mybatis 3.3.0 Log4j配置

    最近做一个SSM学习项目,配置log4j,mybatis用下面的方式配置,不管用,打印不出执行的SQL语句. log4j.logger.java.sql.Connection=DEBUGlog4j.l ...

  6. MyBatis Generator自动生成的配置及使用

    注意:文件名不能有中文字符,不然不能自动生成 找到MyBatis Generator.rar\MyBatis Generator\eclipse里的features和plugins文件,把这两个文件复 ...

  7. myBatis 基础测试 表关联关系配置 集合 测试

    myBatis 基础测试 表关联关系配置 集合 测试 测试myelipse项目源码 sql 下载 http://download.csdn.net/detail/liangrui1988/599388 ...

  8. Spring-MVC开发步骤(入门配置)

    Spring-MVC开发步骤(入门配置) Step1.导包 spring-webmvc Step2.添加spring配置文件 Step3.配置DispatcherServlet 在web.xml中: ...

  9. spring+mybatis的多源数据库配置实战

    前言: 关于spring+mybatis的多源数据库配置, 其实是个老生常谈的事情. 网上的方案出奇的一致, 都是借助AbstractRoutingDataSource进行动态数据源的切换. 这边再无 ...

随机推荐

  1. [转载]TSO、UFO、GSO、LRO、GRO和RSS介绍

    TSO.UFO.GSO.LRO.GRO和RSS介绍 ethtool -k < 网络接口>,ethtool --show-offload < 网络接口>,或者可以看到很多网络接口 ...

  2. Linux驱动 - SPI驱动 之四 SPI数据传输的队列化

    我们知道,SPI数据传输可以有两种方式:同步方式和异步方式.所谓同步方式是指数据传输的发起者必须等待本次传输的结束,期间不能做其它事情,用代码来解释就是,调用传输的函数后,直到数据传输完成,函数才会返 ...

  3. NB-LOT 科普

    最全科普!你一定要了解的NB-IoT 2017-06-19 21:04物联网/操作系统/科普 工信部下发通知推动150万NB-IoT基站落地.NB-IoT汹涌而来.很多网友要求雇佣军科普一篇NB-Io ...

  4. XXXAction-validation.xml文件中报错:Referenced file Contains errors

    我们需要引用与验证器配置相关的dtd文件,这个文件可以在xwork-core-2.3.1.2.jar下找到(xwork-validator-1.0.3.dtd) 网上有很多处理办法,如下所示: 1.直 ...

  5. rails的respond to format

    Here are all the default Rails Mime Types: "*/*" => :all "text/plain" => : ...

  6. ios下编译opencv

    如果想要在ios下编译opencv 需要安装Cmake 这里通过homebrew 来安装cmake ios下打开终端然后先安装 homebrew :(mac 下自带ruby) ruby -e &quo ...

  7. python之数据库的操作(课前准备)

    数据库(Database)是按照数据结构来组织.存储和管理数据的仓库. 上面的就是数据库的定义. 何为数据库,简单的来说,就是我们的大型数据的存放地点. 而我们学习的呢就是数据库的访问层的制作. 何为 ...

  8. 第二天:tomcat体系结构和第一个Servlet

    1.  打war包 2.  Tomcat体系再说明:   问题:如何去配置默认主机???    3.tomcat和servlet在网络中的位置 4.    servlet快速入门案例   1).开发s ...

  9. Ajax入门(一)从0开始到一次成功的GET请求

    什么是服务器 网页浏览过程分析 一个完整的HTTP请求过程,通常有下面7个步骤 建立TCP连接 Web浏览器向Web服务器发送请求命令 Web浏览器发送请求头信息 Web服务器- 应答 Web服务器- ...

  10. 【总结整理】openlayer

    实时路况 http://www.cnblogs.com/gisvip/archive/2012/11/24/2787141.html