Mybatis笔记一:写一个demo

时间:2023-02-14 15:13:59

什么是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主要写的是增删改查之类的

看看我的数据库

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

Mybatis笔记一:写一个demo

看看我的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&num;中多种常用的集合排序方法

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

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

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

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

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

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

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

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

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

随机推荐

  1. ionic 使用sqlite

    昨天被ionic和sqlite折腾一天,怎么也无法实现读取,后来才发现,原来是codova中的sqliteplugin版本问题. 问题:Database location or iosDatabase ...

  2. jQuery点击图片弹出放大可拖动图片查看

    CSS代码: .popup-bigic { position: absolute; ; ; background: #eee; overflow: hidden; ; } .popup-bigic . ...

  3. jQuery Validate 插件&lbrack;表单验证 属性介绍&rsqb;

    详细介绍一下Validate插件 $("#form的Id").validate({ }) 属性 规则 描述 required:true 必须输入的字段 required: &quo ...

  4. java设计模式—多工厂模式

    概念           多个工厂模式,是对普通工厂方法的改进,在普通工厂模式中,如果字符串传递出错,则不能正   确创建对象,而多个工厂模式是提供多个工厂方法,分别创建对象.     多个工厂模式关 ...

  5. tomcat &plus;jenkios

    来源:https://www.cnblogs.com/edward2013/p/5269465.html 1. 安装JDK JDK下载地址:  http://www.oracle.com/techne ...

  6. 51nod--1135 原根 (数论)

    题目: 设m是正整数,a是整数,若a模m的阶等于φ(m),则称a为模m的一个原根.(其中φ(m)表示m的欧拉函数) 给出1个质数P,找出P最小的原根. Input 输入1个质数P(3 <= P ...

  7. navicat premium 破解版

    下载链接:https://pan.baidu.com/s/1oNwtr2hdUN9F452xkji0aQ

  8. Moco服务器jar包实现简易的API搭建

    永远不要停止前进的脚步,就像你不会忘记以前那些窘迫的连一无所有都称不上的裸露的记忆一样.追求永远的打怪升级,武装自己.双手的努力让曾经那些不堪的记忆在时间的长河中渐渐风化隐匿,但请不要忘记它留下的那一 ...

  9. Caffe源码中math&lowbar;functions文件分析

    Caffe源码(caffe version:09868ac , date: 2015.08.15)中有一些重要文件,这里介绍下math_functions文件. 1.      include文件: ...

  10. Django model字段类型&lpar;转&rpar;

    AutoField     一个 IntegerField, 添加记录时它会自动增长. 你通常不需要直接使用这个字段; 如果你不指定主键的话,系统会自动添加一个主键字段到你的 model.(参阅 _自 ...