因为这里是说mybatis的,所以呢 servlet就不做多说了,代码也不在这里贴出来了.

log4j.properties

log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

mybatis-config.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>
<!-- 注意:一定要加在<properties>之后且<typeAliases>之前 -->
     <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<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="gys" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/imooc/config/sqlxml/message.xml" />
</mappers>
</configuration>

message.xml

<?xml version="1.0" encoding="UTF-8" ?> <!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
<where>
<!--以下条件 test="command != null && "".equals(command.trim()) " -->
<!-- <if test="command !=null &amp;&amp !&quot;&quot;.equals(command.trim())">
and COMMAND =#{command}
</if> -->
<if test="command != null and !&quot;&quot;.equals(command.trim())">
and command=#{command}
</if>
<if test="description != null and !&quot;&quot;.equals(description.trim())">
and description like '%' #{description} '%'
</if>
</where>
</select>
<!-- 单个删除 ,这种情况 参数用_parameter -->
<delete id="deleteOne" parameterType="int">
delete from message where ID=#{_parameter}
</delete> <!-- 批量删除 -->
<delete id="deleteBatch" parameterType="java.util.List">
delete from message where ID in (
<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
)
</delete> <!-- 这里的keyProperty对应的是类中的属性,不是数据库中的字段,插入数据返回id主键值 -->
<insert id="insertData" parameterType="com.imooc.bean.Message" useGeneratedKeys="true" keyProperty="id">
insert into message
(COMMAND,DESCRIPTION,CONTENT)
values
(#{command},#{description},#{content})
</insert> <select id="getDataByCommand" parameterType="String" resultMap="MessageResult" resultType="com.imooc.bean.Message">
select ID,COMMAND,DESCRIPTION,CONTENT from message where COMMAND=#{_parameter} limit 1
</select> </mapper>

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; /**
* 访问数据库
* @author gys
*
*/
public class DBAccess {
public SqlSession getSqlSession() throws IOException{
//通过配置文件获取数据库连接信息
Reader reader= Resources.getResourceAsReader("com/imooc/config/mybatis-config.xml");
//通过配置信息构建一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
//通过sqlSessionFactory打开一个数据库回话
SqlSession sqlSession=sqlSessionFactory.openSession();
return sqlSession;
}
}

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; /**
* 和message表相关的数据库操作
* @author gys
*
*/
public class MessageDao {
public List<Message> queryMessageList(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语句
messageList=sqlSession.selectList("message.queryMessageList",message);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession !=null){
sqlSession.close();
}
}
return messageList;
}
/**
* 单条删除
* @param id
*/
public void deleteOne(int id){
DBAccess dbAccess=new DBAccess();
SqlSession sqlSession=null;
try {
sqlSession= dbAccess.getSqlSession();
//通过sqlSession执行sql语句
int count=sqlSession.delete("message.deleteOne",id);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession !=null){
sqlSession.close();
}
}
} /**
* 批量删除
*/
public void deleteBatch(List<Integer> ids){
DBAccess dbAccess=new DBAccess();
SqlSession sqlSession=null;
try {
sqlSession= dbAccess.getSqlSession();
//通过sqlSession执行sql语句
int count=sqlSession.delete("message.deleteBatch",ids);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession !=null){
sqlSession.close();
}
}
} /**
* 插入数据,获取主键
*/
public int insertData(Message message){
DBAccess dbAccess=new DBAccess();
SqlSession sqlSession=null;
int id=0;
try {
sqlSession= dbAccess.getSqlSession();
//通过sqlSession执行sql语句
int count=sqlSession.insert("message.insertData",message);//返回受影响的行数
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession !=null){
sqlSession.close();
}
}
id=message.getId();
return id;//返回插入数据的id
} /**
* 获取单个数据
*/
public Message getDataByCommand(String command){
DBAccess dbAccess=new DBAccess();
SqlSession sqlSession=null;
Message message=null;
try {
sqlSession= dbAccess.getSqlSession();
//通过sqlSession执行sql语句
message=sqlSession.selectOne("message.getDataByCommand",command);//返回受影响的行数
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession !=null){
sqlSession.close();
}
}
return message;//返回插入数据的id
} }

MessageService.java

package com.imooc.service;

import java.util.ArrayList;
import java.util.List; import com.imooc.bean.Message;
import com.imooc.dao.MessageDao; public class MessageService {
public List<Message> queryMessageList(String command,String description){
MessageDao messageDao=new MessageDao();
return messageDao.queryMessageList(command, description);
} //单条删除
public void deleteOne(String id){
if(id!=null && !"".equals(id.trim())){
MessageDao messageDao=new MessageDao();
messageDao.deleteOne(Integer.valueOf(id));
}
} /**
* 批量删除
*/
public void deleteBatch(String[] ids){
MessageDao messageDao=new MessageDao();
List<Integer> list=new ArrayList<Integer>();
if(ids==null){
System.out.println("请选择删除的项目!");
}else{
for(String id:ids){
list.add(Integer.valueOf(id));
}
messageDao.deleteBatch(list);
} }
/**
* 批量删除
*/
public int insertData(Message message){
MessageDao messageDao=new MessageDao();
int id=messageDao.insertData(message);
return id;
} /**
* 获取单个数据
*/
public Message getDataByCommand(String command){
MessageDao messageDao=new MessageDao();
return messageDao.getDataByCommand(command);
} }

这些就是mybatis最基础的模板代码.供以后查找用

mybatis模板的更多相关文章

  1. MyBatis 模板

    mybatis-config.xml: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE co ...

  2. Spring mybatis源码篇章-MybatisDAO文件解析(一)

    前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-SqlSessionFactory 加载指定的mybatis主文件 Mybatis模板文件,其中的属性 ...

  3. springboot mybatis 多数据源配置

    首先导入mybatis等包,这里就不多说. 下面是配置多数据源和mybatis,每个数据源对应一套mybatis模板 数据源1: package com.aaaaaaa.config.datasour ...

  4. SpringBoot+SpringCloud+vue+Element开发项目——集成MyBatis框架

    添加mybatis-spring-boot-starter依赖 pox.xml <!--mybatis--> <dependency> <groupId>org.m ...

  5. Spring mybatis源码篇章-Mybatis主文件加载

    通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-SqlSessionFactory 前话 本文承接前文的内容继续往下扩展,通过Spring与Mybatis的 ...

  6. Mybatis总结一之Mybatis项目的创建

    一.mybatis概念 Mybatis是对象和表之间映射关系的持久层框架. 二.Mybatis的导入与创建 第一步,创建web项目,引入mybatis依赖的jar包----mybatis-3.4.6. ...

  7. Thymeleaf+SpringBoot+Mybatis实现的齐贤易游网旅游信息管理系统

    项目简介 项目来源于:https://github.com/liuyongfei-1998/root 本系统是基于Thymeleaf+SpringBoot+Mybatis.是非常标准的SSM三大框架( ...

  8. spring boot集成mybatis框架

    概述 中文官网:http://www.mybatis.cn 参考教程:https://www.w3cschool.cn/mybatis MyBatis Plus:http://mp.baomidou. ...

  9. Spring从认识到细化了解

    目录 Spring的介绍 基本运行环境搭建 IoC 介绍: 示例使用: 使用说明: 使用注意: Bean的实例化方式 Bean的作用范围的配置: 补充: DI: 属性注入: 补充: IoC的注解方式: ...

随机推荐

  1. HTML5鼠标hover的时候图片放大的效果展示

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  2. JDBC - Oracle PreparedStatement (GeneratedKey kind) ArrayIndexOutOfBoundsException

    问题: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12at oracle.jdbc. ...

  3. ASP.NET MVC几种找不到资源的问题解决办法

    转自:http://www.cnblogs.com/xyang/archive/2011/11/24/2262003.html 在MVC中,controller中的Action和View中的.csht ...

  4. [Hibernate] - Interceptors and events

    Hibernate的拦截器,有很大作用.比如要监控SQL的执行效率等. 参考文档: http://docs.jboss.org/hibernate/orm/3.5/reference/zh-CN/ht ...

  5. Python基础教程【读书笔记】 - 2016/7/24

    希望通过博客园持续的更新,分享和记录Python基础知识到高级应用的点点滴滴! 第九波:第9章  魔法方法.属性和迭代器  在Python中,有的名称会在前面和后面都加上两个下划线,这种写法很特别.已 ...

  6. LitDB笔记

    首先,LitDB存储的不是json,而是bson.这里就有问题了,json是可以无限扩展的,但是bson不行.所有insert的时候需要使用实体类而不是hashtable.但是它又提供了一个叫做Bso ...

  7. 【Struts2学习笔记-3】常量配置

    Struts2常量 配置Struts2常量值有3个地方,1)在struts.properties文件中配置常量:2)在web.xml文件中配置FileterDispatcher指定初始化参数来配置常量 ...

  8. Env:autojump安装使用

    注:这里只介绍我使用的方式,当然不是唯一方式 作用:autojump可以快速进行路径导航,具备记忆历史路径:不仅仅是可以进入当前路径下的某个路径,也可以是其他历史路径 1. 下载 首先,$ git c ...

  9. 25. Reverse Nodes in k-Group

    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If ...

  10. FB Flash Builder 安装错误 ERROR: DW050: - Microsoft Visual C++ 2010 Redistributable Package (x86): Install failed

    这个问题很可能是你的 Microsoft Visual C++ 2010 Redistributable Package (x86) 太新的缘故,所以无法安装成功,导致最终的失败. 在控制面板-程序和 ...