MyBatis_2_MyBatis下载并搭建框架

preivious:MyBatis_1 next:MyBatis_3_SQL动态拼接

===3-1 MyBatis下载并搭建框架=========================================== 

download site: https://github.com/mybatis/mybatis-3/releases

下载:

Latest release 

mybatis-3.4.4.zip

Source code (zip) 里面的test有参照实例

=================================================

MyBatis

1 导入JAR包

2 参照官方演示代码的核心配置文件:src\test\java\org\apache\ibatis\submitted\complex_property\Configuration.xml

configuration.xml:

暂时不用的配置内容先注释掉

 

<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases> -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/micro_message"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- 
  <mappers>
    <mapper resource="com/imooc/config/sqlxml/Message.xml"/>
    <mapper resource="com/imooc/config/sqlxml/Command.xml"/>
    <mapper resource="com/imooc/config/sqlxml/CommandContent.xml"/>
  </mappers>
  -->

</configuration>

 3.Mybatis之SqlSession

  SqlSession的作用

  1)向SQL语句传入参数

  2)执行SQL

  3)获取执行SQL结果

  4)事务的控制

  获得SqlSession:

  1)通过配置文件获取数据库连接相关信息

  2)通过配置信息构建SqlSessionFactory

  3)通过SqlSessionFactory打开数据库会话

DB层:创建SqlSession

DBAccess:

package com.imooc.db;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 访问数据库类
 */
public class DBAccess {
    public SqlSession getSqlSession() throws IOException {
        // 通过配置文件获取数据库连接信息 配置文件路径从SRC包的根路径开始算起
        Reader reader = Resources.getResourceAsReader("com/imooc/config/Configuration.xml");
        // 通过配置信息构建一个SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        // 通过sqlSessionFactory打开一个数据库会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

 DAO层,构筑MyBatis的的DAO:

注意:在finally 的brace({})中,对SQLSession进行关闭,finally中的代码无论是否出异常都会执行

package com.imooc.dao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.imooc.bean.Message;
import com.imooc.db.DBAccess;

/**
 * 和message表相关的数据库操作
 */
public class MessageDao {
    
    /**
     * 根据查询条件查询消息列表
     */
    public List<Message> queryMessageList(String command,String description) {
        DBAccess dbAccess = new DBAccess();
        List<Message> messageList = new ArrayList<Message>();
        SqlSession sqlSession = null;
        try {
            Message message = new Message();
            message.setCommand(command);
            message.setDescription(description);
            sqlSession = dbAccess.getSqlSession();
            // 通过sqlSession执行SQL语句详见(3-2 SQL 基本配置与执行)
            messageList = sqlSession.selectList("Message.queryMessageList", message);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(sqlSession != null) {
                sqlSession.close();
            }
        }
        return messageList;
    }
}

 ---3-2 SQL 基本配置与执行-------------------------------------------------------

1.SQL的配置文件

mapper的namespace(必须)与下面的语句的id组合成唯一的ID(所有的SQL配置文件中此组合必须唯一)

<mapper namespace="Message">

2.执行方式

·SQL 标签 <select> <insert><delete><update>

·SQL标签的resultMap属性与<resultMap>的ID对应

// 通过sqlSession执行SQL语句namespace.id
            messageList = sqlSession.selectList("Message.queryMessageList", message);

<select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">

 

3.检索结果配置

.resultMap的ID在<resultMap>标签中唯一即可,可以与SQL语句标签重复

.如果是主键的话,配置为<id>标签,普通的列为<result>标签

.属性 column为数据库的列名,property为对象类的属性名,jdbcType与java.sql.Type.的名对应

<resultMap type="com.imooc.bean.Message" id="MessageResult">

    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Message">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>

  <select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
    select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE
  </select>
  
</mapper>

 把SQL配置文件配置到核心配置文件Configuration.xml的<mapper>中

<configuration>
<!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases> 
-->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/micro_message"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
   
  <mappers>
    <mapper resource="com/imooc/config/sqlxml/Message.xml"/>
  </mappers>

</configuration>

 

posted @ 2017-04-20 09:39  charles999  阅读(648)  评论(0编辑  收藏  举报