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" ?>

<!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:搭建核心架构的更多相关文章

  1. 通过自动回复机器人学Mybatis:MySQL脚本 + db >> dao >> service >> servlet

    留着参考 makeData.sql delimiter // create procedure make_data() begin declare i int ; do insert into mes ...

  2. 通过自动回复机器人学Mybatis:OGNL+log4j.properties

    imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154 OGNL规则: 从哪里取?(作用域.取值范围,例如封装入一个对象,该对象就是取值范围) ...

  3. 通过自动回复机器人学Mybatis 笔记:接口式编程

    [接口式编程]尚未遇见Spring --> 代码量反而增加 1.增加约定,减少犯错的可能(不用直接去写字符串 修改点1:命名空间 修改点2:增加接口,方法名与配置文件中的id对应 package ...

  4. 通过自动回复机器人学Mybatis笔记:接口式编程

    [接口式编程]尚未遇见Spring --> 代码量反而增加 1.增加约定,减少犯错的可能(不用直接去写字符串 修改点1:命名空间 修改点2:增加接口,方法名与配置文件中的id对应 package ...

  5. 通过自动回复机器人学Mybatis:代码重构(分层)

    imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154 ListServlet.java package com.imooc.servlet; ...

  6. 通过自动回复机器人学Mybatis:原始版本(包括JDBC、pom.xml等)

    imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154 list.jsp <%@ page contentType="text/ ...

  7. MyBatis 基础搭建及架构概述

    目录 MyBatis 是什么? MyBatis 项目构建 MyBatis 整体架构 接口层 数据处理层 基础支持层 MyBatis 是什么? MyBatis是第一个支持自定义SQL.存储过程和高级映射 ...

  8. spring初始(介绍、核心架构)

    1.spring介绍 Spring是个java企业级应用的开源开发框架.主要用来开发Java应用,但是有些扩展是针对构建J2EE平台的web应用.Spring框架目标是简化Java企业级应用开发,并通 ...

  9. 浅析MyBatis(一):由一个快速案例剖析MyBatis的整体架构与运行流程

    MyBatis 是轻量级的 Java 持久层中间件,完全基于 JDBC 实现持久化的数据访问,支持以 xml 和注解的形式进行配置,能灵活.简单地进行 SQL 映射,也提供了比 JDBC 更丰富的结果 ...

随机推荐

  1. ubuntu卸载vmware player

    sudo vmware-installer -u vmware-player 转自: http://zhidao.baidu.com/link?url=lapkBNBGIUz_mo6603CQgi_2 ...

  2. PrintArea打印,@media screen解决移动web开发的多分辨率问题,@media print设置打印的样式

    PrintArea打印,局部DIV打印插件,依赖JQuery. github:https://github.com/RitsC/PrintArea 当打印时需要临时改变页面布局,可以使用 @media ...

  3. Castle.MVC框架介绍

    Castle.MVC目前还在Castle的Sandbox中,只是在源代码管理中有,还没有向外发布版本,这里介绍多时Web的MVC,和Castle的MonoRail相比较,这个MVC可以Asp.Net的 ...

  4. Delphi 发送邮件 通过Office Outlook

    Delphi 发送邮件 通过Office Outlook 网上搜到的Delphi邮件发送系统,绝大多数是使用SMTP协议来发送. 但是事实上它们已经过时了,大多数邮件服务器已经屏蔽了Delphi In ...

  5. 【BZOJ4378】[POI2015]Logistyka 树状数组

    [BZOJ4378][POI2015]Logistyka Description 维护一个长度为n的序列,一开始都是0,支持以下两种操作:1.U k a 将序列中第k个数修改为a.2.Z c s 在这 ...

  6. ArcGIS Runtime SDK for iOS开发系列教程(5)——要素信息的绘制

    在客户端绘制点.线.面要素是GIS应用的基本功能,这一讲我将向大家介绍在iOS中如何来实现这一功能.大家都知道在Flex.Silverlight.js中对于要素的绘制都有一个叫GraphicsLaye ...

  7. mysql数据库如何设置表名大小写不敏感?

    转自:https://blog.csdn.net/iefreer/article/details/8313839 在跨平台的程序设计中要注意到mysql的一些系统变量在windows和linux上的缺 ...

  8. Linux shell 脚本中, $@ 和$# 分别是什么意思?

    转自:https://zhidao.baidu.com/question/412833470.html $@:表示所有脚本参数的内容 $#:表示返回所有脚本参数的个数. 示例:编写如下shell脚本, ...

  9. python相关的报错处理

    1.python3.6编译安装完毕后,使用pip3安装virtualenv,提示找不到ssl模块 原因:因为我们少装了openssl-devel依赖包,所以导致编译后的pip3无法找到ssl模块. 解 ...

  10. JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理

    java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...