Mybatis笔记一:写一个demo
什么是Mybatis?
在Java中,我们连接数据库可以使用最初级的JDBC,但是这样很麻烦,每次都要写好多,所以Mybatis出现了,Mybatis可以帮我们很简单很简单的实现与数据库的读取改写操作
引入文件
- Maven引入一个Mybatis的包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
- 还需要一个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写了我们要加载的类的配置文件,这个我们下面细讲
- 类的配置文件
<?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 !"".equals(command.trim())">and COMMAND =#{command}</if>
<if test="description !=null and !"".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> > 内容列表</div>
<div class="rightCont">
<p class="g_title fix">内容列表 <a class="btn03" href="#">新 增</a> <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>
跳至 <input type='text' value='1' class='allInput w28' /> 页
<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的更多相关文章
- python 学习笔记 12 -- 写一个脚本获取城市天气信息
近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...
- DuiLib学习笔记2——写一个简单的程序
我们要独立出来自己创建一个项目,在我们自己的项目上加皮肤这才是初衷.我的新建项目名为:duilibTest 在duilib根目录下面有个 Duilib入门文档.doc 我们就按这个教程开始入门 首先新 ...
- 根据前面的FtpUtil写一个demo
说说现在开发中一般都是对象化,对于配置文件也不例外. 1.FTPConfig 配置类 /*** * * @author * */public class FTPConfig { private St ...
- shiro入门笔记之第一个demo创建
前言 看到这篇文章之前,可能很多小伙伴都没听过shiro,那么shiro是什么呢?shiro是Apache基金会下一个非常有名的开源项目(项目官网: http://shiro.apache.org/ ...
- 通过写一个Demo展示C#中多种常用的集合排序方法
不多说,程序很简单,就是将集合中的数据进行排序,但使用到的知识点还是比较多的,大牛勿喷,谨献给初学者!直接上程序吧! namespace Demo { /// <summary> /// ...
- 《python灰帽子》学习笔记:写一个windos 调试器(一)
一.开发内容介绍 为了对一个进程进行调试,你首先必须用一些方法把调试器和进程连接起来.所以, 我们的调试器要不然就是装载一个可执行程序然后运行它, 要不然就是动态的附加到一个运行的进程.Windows ...
- DuiLib学习笔记2.写一个简单的程序
我们要独立出来自己创建一个项目,在我们自己的项目上加皮肤这才是初衷.我的新建项目名为:duilibTest 在duilib根目录下面有个 Duilib入门文档.doc 我们就按这个教程开始入门 首先新 ...
- 如何在WTL和MFC中使用duilib及如何静态使用duilib库!(初级讲解 附带一个Demo)
关于duilib的历史,我也就不多说了,能看到这篇文章的人都是有一定了解才能找到这个的. 我直接说下对这个库的基本使用吧. 我个人对一些好技术都是比较感兴趣的. 因为个人原因 喜欢接触一个好技术. 所 ...
- Cocos2dx游戏开发系列笔记13:一个横版拳击游戏Demo完结篇
懒骨头(http://blog.csdn.net/iamlazybone QQ:124774397 ) 写下这些东西的同时 旁边放了两部电影 周星驰的<还魂夜> 甄子丹的<特殊身份& ...
随机推荐
- 使用coobird Thumbnailator生成缩略图
pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...
- POJ2187-Beauty Contest-凸包
平面最远点对 由于点数为1e5,而整数点的情况下,凸包上点的个数为sqrt(M),M为范围. 这样求出凸包之后n^2枚举维护距离就可以了 否则就用旋转卡壳. 这里用了挑战上的做法,比较简洁. #inc ...
- 【XSY2528】道路建设 LCT 可持久化线段树
题目描述 给你一个\(n\)个点\(m\)条边图,\(q\)个询问,每次问你边权在\([l,r]\)之间的边组成的最小生成树(森林)的边权和.强制在线. \(n,m,q\leq 100000\) 题解 ...
- 【CF768G】The Winds of Winter 可持久化线段树 DFS序
题目大意 给定一棵\(n\)个点的树,对于树上每个结点,将它删去,然后可以将得到的森林中任意一个点与其父亲断开并连接到另一颗树上,对每一个点求出森林中所有树\(size\)最大值的最小值. \(n\l ...
- windows下操作linux虚拟机映射网络驱动器中文件提示chmod权限不足解决方案
为了方便操作,linux虚拟机会通过windows下连接网络驱动器的方式共享自己的文件,对于前端来说,我想把gulp放在windows磁盘,操作虚拟机中的php文件,一来节省虚拟机磁盘大小,二来解决虚 ...
- [POJ 1637] Sightseeing tour(网络流)
题意 (混合图的欧拉回路判定) 给你一个既存在有向边, 又存在无向边的图. 问是否存在欧拉回路. \(N ≤ 200, M ≤ 1000\) 题解 难点在于无向边. 考虑每个点的度数限制. 我们先对无 ...
- python3 函数function
def function(arg): pass 变量: 由字母.数字和下划线构成,不能以数字开头,不能任意特殊字符 变量定义规范,使用驼峰式或者下划线式格式 变量定义尽量简明,易懂,方便使用者应用 作 ...
- 【LOJ6036】编码(2-sat)
[LOJ6036]编码(2-sat) 题面 LOJ 题解 很显然的一个暴力: 枚举每个串中的?是什么,然后把和它有前缀关系的串全部给找出来,不合法的连边处理一下,那么直接跑\(2-sat\)就做完了. ...
- 8、16、32-BIT系列单片机区别与特点
一.8位单片机 8031/8051/8751是Intel公司早期的产品 1.8031的特点 8031片内不带程序存储器ROM,使用时用户需外接程序存储器和一片逻辑电路373,外接的程序存储器多为EPR ...
- Centos7下源码编译安装python3.6
测试环境: 操作步骤: 1. 下载Python源码包(python3.6.0) 官网下载地址:https://www.python.org/downloads/ 搜狐下载地址:http://mirro ...