通过自动回复机器人学Mybatis(搭建核心架构)

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>
时间: 2024-11-09 02:43:58

通过自动回复机器人学Mybatis(搭建核心架构)的相关文章

Mybatis的下载并搭建核心架构

下载网站: https://github.com/mybatis/mybatis-3/releases 1.引入web项目下引入mybatis.jar 引入到WebRoot/WEB-INF/lib下 2.配置 mybatis 核心配置文件(这个在mybatis源码包中) mybatis-3-mybatis-3.4.5\src\test\java\org\apache\ibatis\submitted\complex_property\Configuration.xml 将Configuratio

通过自动回复机器人学Mybatis:MySQL脚本 + db&gt;&gt;dao&gt;&gt;service&gt;&gt;servlet

留着参考 makeData.sql delimiter // create procedure make_data() begin declare i int default 1; while i < 1000 do insert into message values(i, 'a', 'b', 'c'); set i = i + 1; end while; end; // call make_data(); DROP PROCEDURE IF EXISTS make_data; Message

通过自动回复机器人学Mybatis(代码重构)

imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154 ListServlet.java package com.imooc.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.servlet.ServletExceptio

通过自动回复机器人学Mybatis(OGNL参考)

imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154

《云计算架构技术与实践》连载(13)2.3 云计算核心架构竞争力衡量维度

版权全部,未经华为书面许可.请勿转载或转发 2.3       云计算核心架构竞争力衡量维度 从将云计算技术引入传统数据中心所带来的独特商业价值角度看,重点能够从开源与节流两个方面来衡量云计算的核心竞争力. 节流(Cost Saving)方面 在业务系统搭建过程中.云计算和虚拟化使得企业及运营商的烟囱式软件应用能够突破应用边界的束缚,充分共享企业范围内.行业范围内.甚至全球范围内公用的"IT资源池",无需採购和安装实际物理形态的server.交换机及存储硬件,而是依赖于向集中的&quo

移动支付平台间接口报文解析技术核心架构实现、及平台交易处理项目全程实录教程

<基于移动支付平台间接口报文解析技术核心架构实现.及平台交易处理项目全程实录>课程讲师:MoMo 课程分类:Java框架适合人群:中级课时数量:52课时用到技术:JavaBean .Spring3.X. SpringMVC. Hibernate3.X.Apache HttpClient 3.x.JUnit4.x.自定义Annotation + java反射技术涉及项目:移动支付平台间接口咨询QQ:1337192913 课程介绍:   本课程抛开理论.以项目为驱动,适用于初次接触报文收发.组装解

移动支付平台间接口报文解析核心架构及平台交易全程实录

移动支付平台间接口报文解析核心架构及平台交易全程实录 (HttpClient+SpringMVC+Spring3+Hibernate3+自定义Annotation) 课程分类:Java框架 适合人群:中级 课时数量:52课时 用到技术:JavaBean .Spring3.X. SpringMVC. Hibernate3.X.Apache HttpClient 3.x.JUnit4.x.自定义Annotation + java反射技术 涉及项目:移动支付平台间接口 咨询qq:1840215592

搭建Lamp架构之一,apache搭建。

一:实验要求1:学会编译安装httpd服务器2:熟悉httpd服务的部署过程及常见配置3:学会构建AWStats日志分析系统4:httpd服务的访问控制客户机的地址限制用户授权限制5:构建虚拟WEB主机基于域名的虚拟主机基于IP地址.端口的虚拟主机二:实验环境1.安装包apr-util-1.4.1.tarapr-1.4.6.tarhttpd-2.4.2.tar2.服务器Linux6.5yum仓库三:实验步骤 卸载原先的httpd服务yum remove httpd2.共享宿主机文件夹3.挂载共享

MyBatis 搭建

MyBatis搭建 引入jar包 log4j-1.2.17.jar     log4j包 mybatis-3.2.2.jar  MyBatis的核心包 mysql-connector-java-5.1.7-bin.jar    数据库的链接包 设置配置文件 引入 log4j.properties 配置文件名 MybatisConfig.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE con