什么是Mybatis?

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

引入文件

  1. Maven引入一个Mybatis的包
  1. <dependency>
  2. <groupId>org.mybatis</groupId>
  3. <artifactId>mybatis</artifactId>
  4. <version>3.5.0</version>
  5. </dependency>
  1. 还需要一个Mybatis的配置文件,可以起名为Mybatis.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <!-- 设置一个默认的连接环境信息 -->
  6. <environments default="mysql_developer">
  7. <environment id="mysql_developer">
  8. <!-- mybatis使用jdbc事务管理方式 -->
  9. <transactionManager type="JDBC"></transactionManager>
  10. <!-- mybatis使用连接池方式来获取连接 -->
  11. <dataSource type="POOLED">
  12. <!-- 配置与数据库交互的4个必要属性,不要直接写,单独写在一个配置文件中 -->
  13. <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
  14. <property name="url" value="jdbc:mysql://127.0.0.1:3306/shuyunquan?serverTimezone=UTC"/>
  15. <property name="username" value="root"/>
  16. <property name="password" value="123"/>
  17. </dataSource>
  18. </environment>
  19. </environments>
  20. <!-- 加载映射文件-->
  21. <mappers>
  22. <mapper resource="config/Message.xml"/>
  23. </mappers>
  24. </configuration>

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

  1. 类的配置文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE mapper PUBLIC
  3. "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <!-- mapper标签都有一个唯一标示,即为命名空间namespace -->
  6. <mapper namespace="Message">
  7. <!--
  8. 数据库查询数据
  9. insert、select、delete、update:sql语句类型
  10. id:sql语句唯一标识
  11. resultType:结果返回值类型-包名+类名 或 基本数据类型
  12. parameterType:匹配字段值-包名+类名 或 基本数据类型
  13. -->
  14. <select id="selectListMessage" parameterType="com.vae.springboot.study.bean.Message" resultType="com.vae.springboot.study.bean.Message">
  15. select * from message where 1=1
  16. <if test="command !=null and !&quot;&quot;.equals(command.trim())">and COMMAND =#{command}</if>
  17. <if test="description !=null and !&quot;&quot;.equals(description.trim())">and DESCRIPTION like '%' #{description} '%'</if>
  18. </select>
  19. <select id="selectOneMessage" parameterType="com.vae.springboot.study.bean.Message" resultType="com.vae.springboot.study.bean.Message">
  20. select * from message where ID=#{ID}
  21. </select>
  22. <!--<insert id="xx1" resultType="xx" parameterType="xxx">-->
  23. <!--insert into tb(c1) values(#{v1})-->
  24. <!--</insert>-->
  25. <delete id="deleteOneMessage" parameterType="com.vae.springboot.study.bean.Message">
  26. delete from message where ID = #{para}
  27. </delete>
  28. <!--<update id="xx3" parameterType="xxx">-->
  29. <!--update advertis set c1 = v1 where c2 =#{v2};-->
  30. <!--</update>-->
  31. </mapper>

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

看看我的数据库

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

看看我的Java Bean

  1. package com.vae.springboot.study.bean;
  2. /**
  3. * 消息表对应的Java Bean
  4. */
  5. public class Message {
  6. private String id;
  7. private String command;
  8. private String description;
  9. private String content;
  10. public String getId() {
  11. return id;
  12. }
  13. public void setId(String id) {
  14. this.id = id;
  15. }
  16. public String getCommand() {
  17. return command;
  18. }
  19. public void setCommand(String command) {
  20. this.command = command;
  21. }
  22. public String getDescription() {
  23. return description;
  24. }
  25. public void setDescription(String description) {
  26. this.description = description;
  27. }
  28. public String getContent() {
  29. return content;
  30. }
  31. public void setContent(String content) {
  32. this.content = content;
  33. }
  34. }

看看我的Controller

  1. package com.vae.springboot.study.Controller;
  2. import com.vae.springboot.study.DB.DBAcess;
  3. import com.vae.springboot.study.bean.Message;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestBody;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import java.io.IOException;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. /**
  13. * 列表页面初始化
  14. */
  15. @Controller
  16. public class ListController {
  17. @ResponseBody
  18. @RequestMapping("/list")
  19. public List<Message> list(@RequestBody Message message) throws IOException {
  20. List<Message> list=new ArrayList<>();
  21. DBAcess dbAcess=new DBAcess();
  22. SqlSession sqlSession = dbAcess.getSqlSession();
  23. System.out.println("---------------"+message.getCommand());
  24. System.out.println("---------------"+message.getDescription());
  25. try {
  26. list =sqlSession.selectList("Message.selectListMessage",message);
  27. return list;
  28. }finally {
  29. sqlSession.close();
  30. }
  31. }
  32. @ResponseBody
  33. @RequestMapping("/getOne")
  34. public List<Message> getOne() throws IOException {
  35. List<Message> list=new ArrayList<>();
  36. DBAcess dbAcess=new DBAcess();
  37. SqlSession sqlSession = dbAcess.getSqlSession();
  38. try {
  39. list =sqlSession.selectList("Message.selectOneMessage",1);
  40. System.out.println(list.get(0));
  41. return list;
  42. }finally {
  43. sqlSession.close();
  44. }
  45. }
  46. @ResponseBody
  47. @RequestMapping("/delete")
  48. public List<Message> delete(@RequestBody Message message) throws IOException {
  49. List<Message> list=new ArrayList<>();
  50. DBAcess dbAcess=new DBAcess();
  51. SqlSession sqlSession = dbAcess.getSqlSession();
  52. System.out.println("---------------"+message.getCommand());
  53. System.out.println("---------------"+message.getDescription());
  54. try {
  55. list =sqlSession.selectList("Message.deleteOneMessage",message);
  56. return list;
  57. }finally {
  58. sqlSession.close();
  59. }
  60. }
  61. }

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

  1. package com.vae.springboot.study.DB;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  6. import java.io.IOException;
  7. import java.io.Reader;
  8. public class DBAcess {
  9. public SqlSession getSqlSession() throws IOException {
  10. Reader reader=Resources.getResourceAsReader("config/Mybatis.xml");
  11. SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
  12. SqlSession sqlSession = sqlSessionFactory.openSession();
  13. return sqlSession;
  14. }
  15. }

测试类

  1. package com.vae.springboot.study.Controller;
  2. import com.vae.springboot.study.DB.DBAcess;
  3. import com.vae.springboot.study.bean.Message;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import java.io.IOException;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class ListControllerTest {
  15. @Test
  16. public void test() throws IOException {
  17. List<Message> list=new ArrayList<>();
  18. DBAcess dbAcess=new DBAcess();
  19. SqlSession sqlSession = dbAcess.getSqlSession();
  20. list = sqlSession.selectList("Message.selectListMessage");
  21. System.out.println(list);
  22. }
  23. @Test
  24. public void getOne() throws IOException {
  25. List<Message> list=new ArrayList<>();
  26. DBAcess dbAcess=new DBAcess();
  27. SqlSession sqlSession = dbAcess.getSqlSession();
  28. try {
  29. list =sqlSession.selectList("Message.selectOneMessage",1);
  30. System.out.println(list.get(0).getId()+list.get(0).getCommand()+list.get(0).getDescription());
  31. }finally {
  32. sqlSession.close();
  33. }
  34. }
  35. }

我的前端,使用Ajax技术

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5. <meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE" />
  6. <title>内容列表页面</title>
  7. <link href="css/all.css" rel="stylesheet" type="text/css" />
  8. <script src="js/jquery-1.8.0.min.js"></script>
  9. </head>
  10. <body style="background: #e1e9eb;">
  11. <form action="" id="mainForm" method="post">
  12. <div class="right">
  13. <div class="current">当前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">内容管理</a> &gt; 内容列表</div>
  14. <div class="rightCont">
  15. <p class="g_title fix">内容列表 <a class="btn03" href="#">新 增</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn03" href="#">删 除</a></p>
  16. <table class="tab1">
  17. <tbody>
  18. <tr>
  19. <td width="90" align="right">指令:</td>
  20. <td>
  21. <input type="text" id="command" class="allInput" value=""/>
  22. </td>
  23. <td width="90" align="right">描述:</td>
  24. <td>
  25. <input type="text" id="description" class="allInput" value=""/>
  26. </td>
  27. <td width="85" align="right"><input type="button" class="tabSub" onclick="refurbishIndex()" value="查 询" /></td>
  28. </tr>
  29. </tbody>
  30. </table>
  31. <div class="zixun fix">
  32. <table class="tab2" width="100%">
  33. <tr>
  34. <th><input type="checkbox" id="all" onclick="#"/></th>
  35. <th>id</th>
  36. <th>指令</th>
  37. <th>描述</th>
  38. <th>操作</th>
  39. </tr>
  40. <tbody id="tbodydata">
  41. </tbody>
  42. </table>
  43. <div class='page fix'>
  44. <b>4</b>
  45. <a href='###' class='first'>首页</a>
  46. <a href='###' class='pre'>上一页</a>
  47. 当前第<span>1/1</span>
  48. <a href='###' class='next'>下一页</a>
  49. <a href='###' class='last'>末页</a>
  50. 跳至&nbsp;<input type='text' value='1' class='allInput w28' />&nbsp;页&nbsp;
  51. <a href='###' class='go'>GO</a>
  52. </div>
  53. </div>
  54. </div>
  55. </div>
  56. </form>
  57. </body>
  58. </html>
  59. <script type="text/javascript">
  60. $(function () {
  61. refurbishIndex();
  62. })
  63. function refurbishIndex(){
  64. var queryData = {
  65. command : $('#command').val(),
  66. description : $('#description').val()
  67. }
  68. $.ajax({
  69. type:"post",
  70. url:"/list",
  71. data:JSON.stringify(queryData),
  72. contentType : "application/json",
  73. success:function (data) {
  74. var str="";
  75. for (i in data) {
  76. str += "<tr>" +
  77. "<td>"+"<input type=\"checkbox\" />"+"</td>"+
  78. "<td align='center'>" + data[i].id + "</td>" +
  79. "<td align='center'>" + data[i].command + "</td>" +
  80. "<td align='center'>" + data[i].description + "</td>" +
  81. "<td>\n" +
  82. "<a href=\"#\">修改</a>\n" +
  83. "<a href=\"#\">删除</a>\n" +
  84. "</td>"
  85. "</tr>";
  86. }
  87. document.getElementById("tbodydata").innerHTML=str;
  88. }
  89. });
  90. }
  91. </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. Redis——redis使用redis-dump,redis-load导出导入数据——【三】

    来源 https://www.cnblogs.com/dadonggg/p/8662455.html https://blog.csdn.net/chenxinchongcn/article/deta ...

  2. 水课 or not

    很不幸,这学期的毛概老师是个老古董,讲的内容也甚是枯燥和迂腐,个人角度是不太喜欢.然而这也仅仅是站在个人感性的角度,唏嘘一下也就够了.听不下去了,写点东西. 有时候会想,是不是随着自己长大,渐渐地对专 ...

  3. LOJ2269 [SDOI2017] 切树游戏 【FWT】【动态DP】【树链剖分】【线段树】

    题目分析: 好题.本来是一道好的非套路题,但是不凑巧的是当年有一位国家集训队员正好介绍了这个算法. 首先考虑静态的情况.这个的DP方程非常容易写出来. 接着可以注意到对于异或结果的计数可以看成一个FW ...

  4. Codeforces551 C. GukiZ hates Boxes

    二分答案 + 贪心 传送门:$>here<$ $Solution$ 二分时间+贪心验证.思维难度主要在验证上,然而坑人的点却在n的取值上.那么先来谈如何验证.在已知时间的条件下,能否用一种 ...

  5. 【XSY2729】欧拉子图 无向图连通性 数学

    题目大意 给你一个\(n\)个点\(m\)条边的无向图(可能有重边),对于这个图的边集的子集(一共有\(2^m\)个),如果其导出的子图的每个联通块内都存在欧拉回路,我们就把答案加上这个子图的边数的平 ...

  6. Qt Creator 编译测试 MQTT-C

    @2018-12-21 [小记] 创建工程步骤: a. File ---> New File or Project ---> Non-Qt Project ---> Plain C ...

  7. UVA10559 Blocks(区间dp)

    有n个带有颜色的方块,没消除一段长度为x的连续的相同颜色的方块可以得到x^2的分数,让你用一种最优的顺序消除所有方块使得得分最多. 输入格式 第一行包含测试的次数t(1≤t≤15) 每个案例包含两行. ...

  8. 低电平ViL

    低电平 编辑 低电平(Vil)指的是保证逻辑门的输入为低电平时所允许的最大输入低电平,当输入电平低于Vil时,则认为输入电平为低电平.   中文名 低电平 外文名 Vil 主要应用 测量电缆和保护连接 ...

  9. CentOS装个NTP时间同步服务器

    服务端: driftfile /var/lib/ntp/drift restrict default nomodify notrap nopeer noquery restrict 127.0.0.1 ...

  10. Class实例在堆中还是方法区中?

    1.JVM中OOP-KLASS模型 在JVM中,使用了OOP-KLASS模型来表示java对象,即:1.jvm在加载class时,创建instanceKlass,表示其元数据,包括常量池.字段.方法等 ...