美文网首页
10分钟从JDBC到Mybatis

10分钟从JDBC到Mybatis

作者: AndyXB | 来源:发表于2016-11-23 17:20 被阅读93次

    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;}
    

    相关文章

      网友评论

          本文标题:10分钟从JDBC到Mybatis

          本文链接:https://www.haomeiwen.com/subject/udsvpttx.html