1. 程式人生 > >通過自動回復機器人學Mybatis(搭建核心架構)

通過自動回復機器人學Mybatis(搭建核心架構)

root -c 驅動 ear resource any 異常 cep driver

imooc視頻學習筆記 ----> URL:http://www.imooc.com/learn/154

MessageDao.java

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;
/**
 * 
 * Dao層需求:1對象能與數據庫交互 2能執行SQL執行
 * Mybatis給dao層提供對象——SqlSession
 * SqlSession的作用:
 * 1、向SQL語句傳入參數
 * 2、執行SQL語句
 * 3、獲取SQL執行結果
 * 4、事務的控制
 * 如何得到SqlSession:
 * 1、通過配置文件獲取數據庫連接的相關信息
 * 2、通過配置信息構建SqlSessionFactory
 * 3、通過SqlSessionFactory打開數據庫會話
 
*/ public class MessageDao { /** * 改成Mybatis的一套 * 根據查詢條件獲取消息列表 */ public List<Message> queryMessageList(String command, String description) { List<Message> messageList = new ArrayList<>(); DBAccess dbAccess = new DBAccess(); SqlSession sqlSession
= null; try { sqlSession = dbAccess.getSqlSession(); // 通過sqlSession執行SQL語句 messageList = sqlSession.selectList("Message.queryMessageList"); } catch (IOException e) { e.printStackTrace(); } finally { // 如果中間發生異常sqlSession可能是null
if (sqlSession != null) { sqlSession.close(); } } return messageList; } public static void main(String[] args) { MessageDao messageDao = new MessageDao(); messageDao.queryMessageList("", ""); } /* // 數據庫驅動 private static final String JDBC_DRIVER = "org.gjt.mm.mysql.Driver"; // 數據庫地址 private static final String DB_URL = "jdbc:mysql://localhost:3306/miro_message"; // 用戶名與密碼 private static final String USER = "root"; private static final String PASS = "19971019"; private static Connection conn = null; // 加載數據庫驅動 static { try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } // 獲取消息列表 public List<Message> queryMessageList(String command, String description) { List<Message> messageList = new ArrayList<>(); // SQL拼接 StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("select ID, COMMAND, DESCRIPTION, CONTENT from MESSAGE where 1=1"); List<String> paramList = new ArrayList<>(); // 判斷指令是否為空 if (command != null && !"".equals(command.trim())) { sqlBuilder.append(" and COMMAND=?"); paramList.add(command); } // 判斷描述是否為空 if (description != null && !"".equals(description.trim())) { sqlBuilder.append(" and DESCRIPTION like ‘%‘ ? ‘%‘"); paramList.add(description); } String sql = sqlBuilder.toString(); PreparedStatement prep = null; ResultSet result = null; try { prep = conn.prepareStatement(sql); // 設置SQL參數 for (int i = 0; i != paramList.size(); ++i) { prep.setString(i+1, paramList.get(i)); } // 執行查找操作 result = prep.executeQuery(); while (result.next()) { // 把查找結果放進List裏 Message message = new Message(); messageList.add(message); message.setId(result.getString("ID")); message.setCommand(result.getString("COMMAND")); message.setDescription(result.getString("DESCRIPTION")); message.setContent(result.getString("CONTENT")); } } catch (SQLException e) { e.printStackTrace(); } // 如果出現異常就返回一個空的List return messageList; }*/ }

Configuration.xml

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

       Copyright 2009-2016 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="org.gjt.mm.mysql.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/miro_message"/>
        <property name="username" value="root"/>
        <property name="password" value="19971019"/>
      </dataSource>
    </environment>
  </environments>
 
  <mappers>
    <mapper resource="com/imooc/config/sqlxml/Message.xml"/>
  </mappers>
  
</configuration>

DBAccess.java

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 {
    // 異常交給Dao層處理
    public SqlSession getSqlSession() throws IOException {
        // STEP-1 通過配置文件獲取數據庫連接的相關信息
        Reader reader = Resources.getResourceAsReader("com/imooc/config/Configuration.xml");
        // STEP-2 通過配置信息構建一個SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        // STEP-3 通過SqlSessionFactory打開數據庫會話
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

Message.xml

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

       Copyright 2009-2016 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標簽,其它的用result標簽 -->
    <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>

  <!-- Message.xml的目的:配置如下的sql語句讓SqlSession讀到並執行 -->
  <!-- id是為了方便sqlSession調用,相同namespace下必須唯一 -->
  <select id="queryMessageList" resultMap="MessageResult">
    select ID, COMMAND, DESCRIPTION, CONTENT from MESSAGE where 1=1
  </select>

</mapper>

通過自動回復機器人學Mybatis(搭建核心架構)