10分钟从JDBC到Mybatis

Mybatis使用简单分为以下几步:

  1. jar包下载
  2. 导入jar包和xml
  3. 配置Configuration.xml
  4. 获取获取SqlSession
  5. 根据相关bean配置相应的xml
  6. 到Configuration.xml加入配置好的xml
  7. 调用SqlSession获取数据

jar包及源码下载https://github.com/mybatis/mybatis-3/releases

导入jar包,并到源码中的以下路径
src/test/java/org/apache/ibatis/submitted/complex_property
复制Configuration.xml和User.xml到配置文件目录下

配置Configuration.xml

<configuration>
    <environments default="development">
      <environment id="development">
        <transactionManager type="JDBC">
          <property name="" value=""/>
        </transactionManager>
        <!-- JDBC相关配置 -->
        <dataSource type="UNPOOLED">
          <property name="driver" value="com.mysql.jdbc.Driver"/>
          <property name="url" value="jdbc:mysql://127.0.0.1:3306/xxx?characterEncoding=utf-8"/>
          <property name="username" value="xxx"/>
          <property name="password" value="xxx"/>
        </dataSource>
      </environment>
    </environments>
</configuration>

获取SqlSession的方法

DBAccess.java中

public SqlSession getSqlSession() throws IOException {
    //通过配置文件获取数据库连接信息
    Reader reader = Resources.getResourceAsReader("com/xxx/config/Configuration.xml");
    //通过配置信息构建一个SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    //通过SqlSessionFactory打开一个数据库会话
    SqlSession sqlSession = sqlSessionFactory.openSession();
    return sqlSession;
}

写一个方法测试是否能够成功获取SqlSession

MessageDao.java中
/**
 * Mybatis
 * 根据查询条件查询消息列表
 */
public List<Message> queryMessageListByMybatis(String command, String description) {
    List<Message> messageList = new ArrayList<Message>();
    DBAccess dbAccess = new DBAccess();
    SqlSession sqlSession = null;
    try {
        sqlSession = dbAccess.getSqlSession();
        // 通过sqlSession执行SQL语句
        // 参数为xml的  namespace. + SQL的id
        messageList = sqlSession.selectList("Message.queryMessageListByMybatis");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (sqlSession != null) sqlSession.close();
    } 
   return messageList;
}

public static void main(String[] args) {
    MessageDao messageDao = new MessageDao();
    messageDao.queryMessageListByMybatis("", "");
}

重命名User.xml为自定义bean相关的,以select语句为例

<!-- Message.xml中 -->

<mapper namespace="Message">
<!-- type为bean位置  id自定义且唯一 -->
  <resultMap type="com.xxx.bean.Message" id="MessageResult">
<!-- id标签对应数据库主键  result标签对应其他字段 -->
    <id column="ID" jdbcType="INTEGER" property="id"/>
<!-- column对应字段名  property对应bean属性名 -->
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>

  <!-- id自定义且唯一  resultMap对应上方自定义id -->
  <!--parameterType参数只能传一个-->
  <select id="queryMessageListByMybatis" parameterType="com.xxx.bean.Message" resultMap="MessageResult">
    SELECT ID,COMMAND,DESCRIPTION,CONTENT FROM MESSAGE where 1=1
    <!--转义字符  "对应&quot;   &对应&amp;  &&可以用and替换-->
    <if test="command!=null&amp;&amp;!&quot;&quot;.equals(command.trim())">
      AND COMMAND=#{command}
    </if>
    <if test="description!=null and !&quot;&quot;.equals(description.trim())">
      AND DESCRIPTION like '%' #{description} '%'
    </if>
  </select>
</mapper>

再回到Configuration.xml中添加mappers到configuration标签中

<!-- 查询实例 -->
    <mappers>
      <mapper resource="com/xxx/config/sqlxml/Message.xml"/>
    </mappers>

到这里,已经可以成功调用了啦~

DAO层中调用

/**
 * Mybatis
 * 根据查询条件查询消息列表
 */
public List<Message> queryMessageListByMybatis(String command, String description) {
    List<Message> messageList = new ArrayList<Message>();
    DBAccess dbAccess = new DBAccess();
    SqlSession sqlSession = null;
    try {
        sqlSession = dbAccess.getSqlSession();
        Message message = new Message();
        message.setCommand(command);
        message.setDescription(description);
        // 通过sqlSession执行SQL语句
        // 参数1:SQL语句id   参数2:传递的参数,只能传一个
        messageList = sqlSession.selectList("Message.queryMessageListByMybatis", message);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (sqlSession != null) sqlSession.close();
    }
    return messageList;}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,838评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,242评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,999评论 6 342
  • 1 引言# 本文主要讲解JDBC怎么演变到Mybatis的渐变过程,重点讲解了为什么要将JDBC封装成Mybait...
    七寸知架构阅读 76,699评论 36 979
  • 学生问老师:什么叫辨证法。 老师笑答:我先问几个问题,打个比方,假如有一富人与一穷人相伴而行,在路上发现一笔巨款,...
    应果阅读 182评论 0 1