先到官网了解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. Vue导出ZIP

    Export2Zip /* eslint-disable */ require('script-loader!file-saver'); import JSZip from 'jszip' expor ...

  2. docker批量操作容器

    author:headsen chen date: 2019-08-07  15:26:46 列出所有的容器 ID docker ps -aq 停止所有的容器 docker stop $(docker ...

  3. ZingChart 隐藏数据点

    正常情况下 zingChart 的数据点会显示到图表中,但是如果数据点很多的情况下,可能会让你无法准确的预测趋势,而且也不美观 在 js 配置中添加最多允许显示的数据点,超过这个值将不显示数据点 效果 ...

  4. 【444】Data Analysis (shp, arcpy)

      ABS suburbs data of AUS 1. Dissolve Merge polygons with the same attribute of "SA2_NAME16&quo ...

  5. Spring Cloud API网关服务 5.2

    为什么需要API网关 通过前面内容的学习,我们已经可以构建一个简单的微服务架构系统.这个系统可以使用Spring Boot实现微服务的开发,使用Spring Cloud Eureka实现注册中心以及服 ...

  6. Spring MVC 为控制器添加通知与处理异常

    与Spring AOP一样,Spring MVC也能够给控制器加入通知,它主要涉及4个注解: •@ControllerAdvice,主要作用于类,用以标识全局性的控制器的拦截器,它将应用于对应的控制器 ...

  7. k8s中正确删除一个pod

    1.先删除pod 2.再删除对应的deployment 否则只是删除pod是不管用的,还会看到pod,因为deployment.yaml文件中定义了副本数量 实例如下: 删除pod [root@tes ...

  8. 04点睛Spring4.1-资源调用

    转发:https://www.iteye.com/blog/wiselyman-2210666 4.1 Resource spring用来调用外部资源数据的方式 支持调用文件或者是网址 在系统中调用p ...

  9. C# .NET WINFORM MUTEX 互斥

    static class Program 里的全局变量: static System.Threading.Mutex appMutex; Main 方法里的内容: string exeName = & ...

  10. c# 基础类型探索

    一.前言 本章节主要是探索 C# 的基本类型,一直以来我本人常用都是 int .double.bool.decimal.string 这五个类型,其对其它类型没有认真了解过.只是以前在学习的时候背了些 ...