先到官网了解mybatis的语法:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html

前端用了thymeleaf和vue.js,效果图和demo地址:https://gitee.com/cainiaoA/mybatis

thymeleaf获取java请求头  ctx='http://localhost:8017/
<script th:inline="javascript"> var ctx = [[@{/}]]; </script>

然后在pom.xml添加相关的引用

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tushu</groupId>
<artifactId>tushu</artifactId>
<version>1.0.0</version>
<name>tushu</name>
<description>练习</description> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<!--spring-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-data-jpa</artifactId>-->
<!--</dependency>-->
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>5.1.21</scope>
</dependency> <!--引入druid-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency> <dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta9</version>
</dependency> <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Alpha6</version>
</dependency> <!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- elastic search -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 用了 elasticsearch 就要加这么一个,不然要com.sun.jna.Native 错误 -->
<dependency>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
<version>3.0.9</version>
</dependency> <!-- thymeleaf legacyhtml5 模式支持 -->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency> <dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.2.1</version>
</dependency> <!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency> <!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- hsqldb -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
</dependencies>
<!--打包成插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

然后编写application.yml的相关配置

server:
port: 8017 spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
jackson:
date-format: yyyy-MM-dd HH:mm:ss #如果使用字符串表示,用这行设置格式
timezone: GMT+8
serialization:
write-dates-as-timestamps: false #使用时间戳,使用数值timestamp表示日期 mybatis:
# 搜索指定包别名
typeAliasesPackage: com.tushu.**.domain
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*Mapper.xml

mybatis相关配置

<?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> <settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>

然后就行相关的ioc和mybatis的数据文件操作

先编写domain,就是数据的model

package com.tushu.book.domain;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map; public class BaseEntity implements Serializable { /** 请求参数 */
private Map<String, Object> params; public Map<String, Object> getParams()
{
if (params == null)
{
params = new HashMap<>();
}
return params;
} public void setParams(Map<String, Object> params)
{
this.params = params;
}
}
package com.tushu.book.domain;

import java.util.Date;

public class books extends BaseEntity {
/**
* 编号
*/
private int id;
/**
* 书名
*/
private String title;
/**
* 价格
*/
private double price;
/**
* 出版日期
*/
private Date publishDate; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public double getPrice() {
return price;
} public void setPrice(double price) {
this.price = price;
} public Date getPublishDate() {
return publishDate;
} public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
} @Override
public String toString() {
return "books{" +
"id=" + id +
", title='" + title + '\'' +
", price=" + price +
", publishDate=" + publishDate +
'}';
}
}

然后编写mybatis数据操作,接口文件格式(xxxMapper.java)

package com.tushu.book.mapper;

import com.tushu.book.domain.books;

import java.util.List;

public interface BooksMapper {

    public int addBook(books model);

    public int updateBook(books model);

    public int deleteBook(int id);

    public List<books> queryBook(books model);
}

数据SQL语句的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="com.tushu.book.mapper.BooksMapper"><!--xxxMapper所在的包--!> <resultMap type="books" id="booksResult">
<id property="id" column="id"/>
<result property="title" column="title"/>
<result property="price" column="price"/>
<result property="publishDate" column="publishDate"/>
<!--<association property="dept" column="dept_id" javaType="SysDept" resultMap="deptResult" />-->
<!--<collection property="roles" javaType="java.util.List" resultMap="RoleResult" />-->
</resultMap> <!--<resultMap id="deptResult" type="SysDept">-->
<!--<id property="deptId" column="dept_id" />-->
<!--<result property="parentId" column="parent_id" />-->
<!--</resultMap>--> <!--<resultMap id="RoleResult" type="SysRole">-->
<!--<id property="roleId" column="role_id" />-->
<!--</resultMap>--> <select id="queryBook" parameterType="books" resultMap="booksResult">
select * from books where 1=1
<if test="title != null and title != ''">
AND title=#{title}
</if>
<if test="price != null and price >0 ">
AND price = #{price}
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
AND date_format(publishDate,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
AND date_format(publishDate,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
<!-- 数据范围过滤 ${params.dataScope} --> </select> <delete id="deleteBook" parameterType="int">
delete from books where id = #{id}
</delete> <update id="updateBook" parameterType="books">
update books
<set>
<if test="title != null and title != ''">title = #{title},</if>
<if test="price != null and price >0 ">price = #{price},</if>
publishDate = sysdate()
</set>
where id = #{id}
</update> <insert id="addBook" parameterType="books" useGeneratedKeys="true" keyProperty="id">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into books(
<if test="id != null and id > 0">id,</if>
<if test="title != null and title != '' ">title,</if>
<if test="price != null and price > 0 ">price,</if>
publishDate
)values(
<if test="id != null and id > 0">#{id},</if>
<if test="title != null and title != ''">#{title},</if>
<if test="price != null and price >0 ">#{price},</if>
sysdate()
)
</insert> </mapper>

然后是是ico的实现

接口

package com.tushu.book.service;

import com.tushu.book.domain.books;

import java.util.List;

public interface IBooksService {
public int addBook(books model); public int updateBook(books model); public int deleteBook(int id); public List<books> queryBook(books model);
}

实现类(逻辑),添加@Service注解和以接口名称+Impl结尾命名

package com.tushu.book.service.impl;

import com.tushu.book.domain.books;
import com.tushu.book.mapper.BooksMapper;
import com.tushu.book.service.IBooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class IBooksServiceImpl implements IBooksService {
@Autowired
private BooksMapper booksMapper; public int addBook(books model) {
return booksMapper.addBook(model);
} public int updateBook(books model) {
return booksMapper.updateBook(model);
} public int deleteBook(int id) {
return booksMapper.deleteBook(id);
} public List<books> queryBook(books model) {
return booksMapper.queryBook(model);
}
}

然后就是控制器的调用

package com.tushu.book.controller;

import com.tushu.book.domain.books;
import com.tushu.book.service.IBooksService;
import com.tushu.book.service.ITestDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import java.util.List; @Controller
@RequestMapping("/system/books")
public class bookscontroller {
private String prefix = "system/books";
@Autowired
IBooksService ibooksService;
@Autowired
ITestDataService testDataService; //页面
@RequiresPermissions("system:books:view")
@GetMapping()
public String books() {
return prefix;
}
//查询
@ResponseBody
@PostMapping("/query")
public List<books> querybook(@Validated books model){
List<books> data = ibooksService.queryBook(model);
return data;
}
//添加
@ResponseBody
@PostMapping("/add")
public books addBook(@Validated books model){
int id = ibooksService.addBook(model);
return model;
}
//修改
@ResponseBody
@PostMapping("/updatebook")
public boolean updatebook(@Validated books model){
int row = ibooksService.updateBook(model);
return row >= 0 ? true:false;
}
//删除
@ResponseBody
@GetMapping("/deletebook/{id}")
public boolean deletebook(@PathVariable("id") int id){
int row = ibooksService.deleteBook(id);
return row >= 0 ? true:false;
} @ResponseBody
@GetMapping("/speak/{str}")
public String speak(@PathVariable("str") String str){
return testDataService.speak(str);
} @ResponseBody
@RequestMapping("/getByName")
public String getByName(String name){
return "hi ,welcome to " + name;
}
}

springmvc+mybatis的增删改查入门的更多相关文章

  1. ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)

    ssm 框架实现增删改查 SpringBoot 项目整合 一.项目准备 1.1 ssm 框架环境搭建 1.2 项目结构图如下 1.3 数据表结构图如下 1.4 运行结果 二.项目实现 1. Emplo ...

  2. [NewLife.XCode]增删改查入门

    NewLife.XCode是一个有10多年历史的开源数据中间件,由新生命团队(2002~2019)开发完成并维护至今,以下简称XCode. 整个系列教程会大量结合示例代码和运行日志来进行深入分析,蕴含 ...

  3. 学习MyBatis必知必会(5)~了解myBatis的作用域和生命周期并抽取工具类MyBatisUtil、mybatis执行增删改查操作

    一.了解myBatis的作用域和生命周期[错误的使用会导致非常严重的并发问题] (1)SqlSessionFactoryBuilder [ 作用:仅仅是用来创建SqlSessionFactory,作用 ...

  4. Spring Boot入门系列(六)如何整合Mybatis实现增删改查

    前面介绍了Spring Boot 中的整合Thymeleaf前端html框架,同时也介绍了Thymeleaf 的用法.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/z ...

  5. springMVC操作mongoDB增删改查

    下面是mongoDb简单的增删改查(新闻类) 附:query.addCriteria(Criteria.where("modelId").ne("").ne(n ...

  6. MyBatis的增删改查。

    数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改,并且对程序接口做了一些调整,以及对一些问题进行了解答. 1.调整后的结构图: 2.连接数据库文件配置分离: 一般的程序都会把连 ...

  7. MyBatis批量增删改查操作

      前文我们介绍了MyBatis基本的增删该查操作,本文介绍批量的增删改查操作.前文地址:http://blog.csdn.net/mahoking/article/details/43673741 ...

  8. 上手spring boot项目(三)之spring boot整合mybatis进行增删改查的三种方式。

    1.引入依赖. <!--springboot的web起步依赖--><dependency> <groupId>org.springframework.boot< ...

  9. 上手spring boot项目(三)之spring boot整合mybatis进行增删改查

    使用mybatis框架进行增删改查大致有两种基础方式,一种扩展方式.两种基础方式分别是使用xml映射文件和使用方法注解.扩展方式是使用mybatis-plus的方式,其用法类似于spring-data ...

随机推荐

  1. mkimage工具的用法

    1. mkimage都支持哪些压缩格式 none, gzip, bzip2等 2. 参考资料 这里

  2. Zabbix3.4指定用户才能收到报警的配置

    Zabbix3.4指定用户才能收到报警的配置 .下载python微信脚本 #安装simplejson wget https://pypi.python.org/packages/f0/07/26b51 ...

  3. pytorch如何先初始化变量,然后再赋值

    下面是定义初始化 #初始化输入的张量 - torch.empty是返回一个包含未初始化数据的张量 self.input = torch.empty(size=(self.opt.batchsize, ...

  4. k8s-基础环境配置(六)

    hostname配置1)修改主机名hostnamectl set-hostname xxx2)加入主机映射vim /etc/hosts……关闭selinuxsed -i '/^SELINUX/s/=. ...

  5. linux记录-安装elk记录(参考博文)

    什么是ELK? 通俗来讲,ELK是由Elasticsearch.Logstash.Kibana .filebeat三个开源软件的组成的一个组合体,这三个软件当中,每个软件用于完成不同的功能,ELK 又 ...

  6. 123457123457#0#----com.MC.konglongtianse222----前拼后广--恐龙填色mc-mc1111

    com.MC.konglongtianse222----前拼后广--恐龙填色mc

  7. 报错:WARN [WorkerSender[myid=1]:QuorumCnxManager@584] - Cannot open channel to 2 at election address /x.x.x.x:3888

    报错背景: zookeeper安装完成之后,启动之后正常,但是查看log文件zookeeper.log时发现报错. 报错现象: -- ::, [myid:] - INFO [WorkerSender[ ...

  8. bladex调用网关使用oauth2统一获取授权

    一:启动网关服务(需要启动其它服务,如:AuthApplication .UserApplication.BladeLogApplication,及自己添加的代码服务) 二:http://localh ...

  9. LeetCode_342. Power of Four

    342. Power of Four Easy Given an integer (signed 32 bits), write a function to check whether it is a ...

  10. js判断图片加载完成

    <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content=&quo ...