什么是Mybatis?

在Java中,我们连接数据库可以使用最初级的JDBC,但是这样很麻烦,每次都要写好多,所以Mybatis出现了,Mybatis可以帮我们很简单很简单的实现与数据库的读取改写操作

引入文件

  1. Maven引入一个Mybatis的包
        <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
  1. 还需要一个Mybatis的配置文件,可以起名为Mybatis.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> <!-- 设置一个默认的连接环境信息 -->
<environments default="mysql_developer">
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="JDBC"></transactionManager>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="POOLED">
<!-- 配置与数据库交互的4个必要属性,不要直接写,单独写在一个配置文件中 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/shuyunquan?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments> <!-- 加载映射文件-->
<mappers>
<mapper resource="config/Message.xml"/>
</mappers> </configuration>

这里Mybatis写了连接数据库的几个要素,还有下面的mappers写了我们要加载的类的配置文件,这个我们下面细讲

  1. 类的配置文件
<?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 -->
<mapper namespace="Message">
<!--
数据库查询数据
insert、select、delete、update:sql语句类型
id:sql语句唯一标识
resultType:结果返回值类型-包名+类名 或 基本数据类型
parameterType:匹配字段值-包名+类名 或 基本数据类型
--> <select id="selectListMessage" parameterType="com.vae.springboot.study.bean.Message" resultType="com.vae.springboot.study.bean.Message">
select * from message where 1=1
<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>
</select> <select id="selectOneMessage" parameterType="com.vae.springboot.study.bean.Message" resultType="com.vae.springboot.study.bean.Message">
select * from message where ID=#{ID}
</select>
<!--<insert id="xx1" resultType="xx" parameterType="xxx">-->
<!--insert into tb(c1) values(#{v1})-->
<!--</insert>--> <delete id="deleteOneMessage" parameterType="com.vae.springboot.study.bean.Message">
delete from message where ID = #{para}
</delete> <!--<update id="xx3" parameterType="xxx">-->
<!--update advertis set c1 = v1 where c2 =#{v2};-->
<!--</update>--> </mapper>

这个其实,我想取的数据库,对应的字段我建立了一个对应的Java Bean,然后这里xml主要写的是增删改查之类的

看看我的数据库

两个配置文件复制一下,看看我的数据库

看看我的Java Bean

package com.vae.springboot.study.bean;

/**
* 消息表对应的Java Bean
*/
public class Message {
private String id;
private String command;
private String description;
private String content; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getCommand() {
return command;
} public void setCommand(String command) {
this.command = command;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
}
}

看看我的Controller

package com.vae.springboot.study.Controller;

import com.vae.springboot.study.DB.DBAcess;
import com.vae.springboot.study.bean.Message;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; /**
* 列表页面初始化
*/
@Controller
public class ListController { @ResponseBody
@RequestMapping("/list")
public List<Message> list(@RequestBody Message message) throws IOException { List<Message> list=new ArrayList<>();
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
System.out.println("---------------"+message.getCommand());
System.out.println("---------------"+message.getDescription());
try {
list =sqlSession.selectList("Message.selectListMessage",message);
return list;
}finally {
sqlSession.close();
} } @ResponseBody
@RequestMapping("/getOne")
public List<Message> getOne() throws IOException { List<Message> list=new ArrayList<>();
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
list =sqlSession.selectList("Message.selectOneMessage",1);
System.out.println(list.get(0));
return list;
}finally {
sqlSession.close();
} } @ResponseBody
@RequestMapping("/delete")
public List<Message> delete(@RequestBody Message message) throws IOException { List<Message> list=new ArrayList<>();
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
System.out.println("---------------"+message.getCommand());
System.out.println("---------------"+message.getDescription());
try {
list =sqlSession.selectList("Message.deleteOneMessage",message);
return list;
}finally {
sqlSession.close();
} } }

由于sqlSessionFactory经常会需要创建,所以我们把创建sqlSessionFactory返回sqlSession封装一下,就叫DBAcess

package com.vae.springboot.study.DB;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException;
import java.io.Reader; public class DBAcess { public SqlSession getSqlSession() throws IOException {
Reader reader=Resources.getResourceAsReader("config/Mybatis.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}

测试类

package com.vae.springboot.study.Controller;

import com.vae.springboot.study.DB.DBAcess;
import com.vae.springboot.study.bean.Message;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; @RunWith(SpringRunner.class)
@SpringBootTest
public class ListControllerTest {
@Test
public void test() throws IOException {
List<Message> list=new ArrayList<>(); DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
list = sqlSession.selectList("Message.selectListMessage");
System.out.println(list);
} @Test
public void getOne() throws IOException { List<Message> list=new ArrayList<>();
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
list =sqlSession.selectList("Message.selectOneMessage",1);
System.out.println(list.get(0).getId()+list.get(0).getCommand()+list.get(0).getDescription());
}finally {
sqlSession.close();
} }
}

我的前端,使用Ajax技术

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE" />
<title>内容列表页面</title>
<link href="css/all.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.0.min.js"></script>
</head>
<body style="background: #e1e9eb;">
<form action="" id="mainForm" method="post">
<div class="right">
<div class="current">当前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">内容管理</a> &gt; 内容列表</div>
<div class="rightCont">
<p class="g_title fix">内容列表 <a class="btn03" href="#">新 增</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn03" href="#">删 除</a></p>
<table class="tab1">
<tbody>
<tr>
<td width="90" align="right">指令:</td>
<td>
<input type="text" id="command" class="allInput" value=""/>
</td>
<td width="90" align="right">描述:</td>
<td>
<input type="text" id="description" class="allInput" value=""/>
</td>
<td width="85" align="right"><input type="button" class="tabSub" onclick="refurbishIndex()" value="查 询" /></td>
</tr>
</tbody>
</table>
<div class="zixun fix"> <table class="tab2" width="100%">
<tr>
<th><input type="checkbox" id="all" onclick="#"/></th>
<th>id</th>
<th>指令</th>
<th>描述</th>
<th>操作</th>
</tr> <tbody id="tbodydata"> </tbody>
</table> <div class='page fix'>
共 <b>4</b> 条
<a href='###' class='first'>首页</a>
<a href='###' class='pre'>上一页</a>
当前第<span>1/1</span>页
<a href='###' class='next'>下一页</a>
<a href='###' class='last'>末页</a>
跳至&nbsp;<input type='text' value='1' class='allInput w28' />&nbsp;页&nbsp;
<a href='###' class='go'>GO</a>
</div>
</div>
</div>
</div>
</form>
</body>
</html> <script type="text/javascript"> $(function () {
refurbishIndex();
}) function refurbishIndex(){ var queryData = {
command : $('#command').val(),
description : $('#description').val()
} $.ajax({
type:"post",
url:"/list",
data:JSON.stringify(queryData),
contentType : "application/json",
success:function (data) {
var str="";
for (i in data) {
str += "<tr>" +
"<td>"+"<input type=\"checkbox\" />"+"</td>"+
"<td align='center'>" + data[i].id + "</td>" +
"<td align='center'>" + data[i].command + "</td>" +
"<td align='center'>" + data[i].description + "</td>" +
"<td>\n" +
"<a href=\"#\">修改</a>\n" +
"<a href=\"#\">删除</a>\n" +
"</td>"
"</tr>";
} document.getElementById("tbodydata").innerHTML=str; }
});
}
</script>

Mybatis笔记一:写一个demo的更多相关文章

  1. python 学习笔记 12 -- 写一个脚本获取城市天气信息

    近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...

  2. DuiLib学习笔记2——写一个简单的程序

    我们要独立出来自己创建一个项目,在我们自己的项目上加皮肤这才是初衷.我的新建项目名为:duilibTest 在duilib根目录下面有个 Duilib入门文档.doc 我们就按这个教程开始入门 首先新 ...

  3. 根据前面的FtpUtil写一个demo

    说说现在开发中一般都是对象化,对于配置文件也不例外. 1.FTPConfig 配置类 /*** * * @author  * */public class FTPConfig { private St ...

  4. shiro入门笔记之第一个demo创建

    前言 看到这篇文章之前,可能很多小伙伴都没听过shiro,那么shiro是什么呢?shiro是Apache基金会下一个非常有名的开源项目(项目官网: http://shiro.apache.org/ ...

  5. 通过写一个Demo展示C#中多种常用的集合排序方法

    不多说,程序很简单,就是将集合中的数据进行排序,但使用到的知识点还是比较多的,大牛勿喷,谨献给初学者!直接上程序吧! namespace Demo { /// <summary> /// ...

  6. 《python灰帽子》学习笔记:写一个windos 调试器(一)

    一.开发内容介绍 为了对一个进程进行调试,你首先必须用一些方法把调试器和进程连接起来.所以, 我们的调试器要不然就是装载一个可执行程序然后运行它, 要不然就是动态的附加到一个运行的进程.Windows ...

  7. DuiLib学习笔记2.写一个简单的程序

    我们要独立出来自己创建一个项目,在我们自己的项目上加皮肤这才是初衷.我的新建项目名为:duilibTest 在duilib根目录下面有个 Duilib入门文档.doc 我们就按这个教程开始入门 首先新 ...

  8. 如何在WTL和MFC中使用duilib及如何静态使用duilib库!(初级讲解 附带一个Demo)

    关于duilib的历史,我也就不多说了,能看到这篇文章的人都是有一定了解才能找到这个的. 我直接说下对这个库的基本使用吧. 我个人对一些好技术都是比较感兴趣的. 因为个人原因 喜欢接触一个好技术. 所 ...

  9. Cocos2dx游戏开发系列笔记13:一个横版拳击游戏Demo完结篇

    懒骨头(http://blog.csdn.net/iamlazybone QQ:124774397 ) 写下这些东西的同时 旁边放了两部电影 周星驰的<还魂夜> 甄子丹的<特殊身份& ...

随机推荐

  1. IntelliJ IDEA Tomcat启动VM Options配置

    -server -XX:PermSize=512M -XX:MaxPermSize=1024m -Dfile.encoding=UTF-8 JDK8中用metaspace代替permsize,因此在许 ...

  2. #194 sequence(搜索+动态规划+主席树)

    考虑按顺序暴搜子序列.如果序列中的数两两不同,显然每次给上一个找到的子序列添上后缀最小值,即为下一个要找的子序列.如果不能再加了就回溯继续考虑后缀次小.第三小……值,直到找到k个子序列. 有重复的数后 ...

  3. Java大数练习

    大数阶乘 题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=28 import java.io.*; import java.util.*; ...

  4. codeforces553C Love Triangles

    题目链接:codeforces553C Love Triangles 我们来看一下对于一个合法三角形可能出现的边 我们发现,在确定了两边之后,第三条边是什么也就随之确定了 我们用\(1\)表示\(lo ...

  5. MT【246】方程根$\backsim$图像交点

    已知函数$f(x)=x^2+x-2$,若$g(x)=|f(x)|-f(x)-2mx-2m^2$ 有三个不同的零点,则$m$的取值范围_____ 分析:等价于$h(x)=|f(x)|-f(x),t(x) ...

  6. Logger.error方法之打印错误异常的详细堆栈信息

    一.问题场景 使用Logger.error方法时只能打印出异常类型,无法打印出详细的堆栈信息,使得定位问题变得困难和不方便. 二.先放出结论 Logger类下有多个不同的error方法,根据传入参数的 ...

  7. visual studio 阅读 linux-kernel

    @2018-12-13 [小记] 使用 visual studio 阅读 linux-kernel 方法 a. 文件 ---> 新建 --->从现有代码创建项目 b. 指定项目存储位置,命 ...

  8. 【转】无法获得锁 /var/lib/dpkg/lock - open (11: 资源暂时不可用) ubuntu 安装vim 及遇到的错误处理

    今天,处理完问题,闲来无事,打算在虚拟机中的Ubuntu中练习shell脚本编写. 无奈,虚拟机系统所装的只有vi,这个编辑软件对于我们来说还是比较不习惯的,所以打算安装vim.好了,闲言少叙. 安装 ...

  9. 「NOI2014」购票 解题报告

    「NOI2014」购票 写完了后发现写的做法是假的...然后居然过了,然后就懒得管正解了. 发现需要维护凸包,动态加点,询问区间,强制在线 可以二进制分组搞,然后你发现在树上需要资瓷撤回,然后暴力撤回 ...

  10. HDU 6319 Problem A. Ascending Rating(单调队列)

    要求一个区间内的最大值和每次数过去最大值更新的次数,然后求每次的这个值异或 i 的总和. 这个序列一共有n个数,前k个直接给出来,从k+1到n个数用公式计算出来. 因为要最大值,所以就要用到单调队列, ...