SpringBoot 使用Mybatis操作mysql示例
1.准备数据库
创建数据库
create databases baodanjia; 创建帐号
create user 'baodanjia'@'%' identified by '123456' grant all privileges on baodanjia.* to 'baodanjia'@'%'; flush privileges; 创建表
mysql -ubaodanjia -p123456 use baodanjia; CREATE TABLE `admin` (
`id` varchar(50) NOT NULL,
`user_name` varchar(20) DEFAULT NULL,
`user_pwd` varchar(50) DEFAULT NULL,
`nick_name` varchar(50) DEFAULT NULL,
`remark` varchar(50) DEFAULT NULL,
`err_count` int(11) DEFAULT NULL,
`gmt_create` datetime DEFAULT NULL,
`gmt_modified` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.创建springboot项目
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.inslife</groupId>
<artifactId>baodanjia</artifactId>
<version>1.0-SNAPSHOT</version> <name>baodanjia</name>
<url>http://bdj.in-s-life.com</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
src/main/resources/application.yaml
server:
port: 9090
spring:
application:
name: baodanjia
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/baodanjia?useUnicode=true&characterEncoding=UTF-8
username: baodanjia
password: 123456
thymeleaf:
cache: false
encoding: utf-8
logging:
level:
com.inslife.mapper: debug
mybatis:
mapper-locations: classpath:mapper/*.xml
src/main/resources/mapper/AdminMapper.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.inslife.mapper.AdminMapper">
<resultMap id="BaseResultMap" type="com.inslife.model.Admin">
<id property="id" column="id" jdbcType="VARCHAR"/>
<result property="user_name" column="user_name" jdbcType="VARCHAR"/>
<result property="user_pwd" column="user_pwd" jdbcType="VARCHAR"/>
<result property="nick_name" column="nick_name" jdbcType="VARCHAR"/>
<result property="remark" column="remark" jdbcType="VARCHAR"/>
<result property="err_count" column="err_count" jdbcType="INTEGER"/>
<result property="gmt_create" column="gmt_create" jdbcType="TIMESTAMP"/>
<result property="gmt_modified" column="gmt_modified" jdbcType="TIMESTAMP"/>
</resultMap>
<insert id="insert" parameterType="com.inslife.model.Admin">
insert into admin (id, user_name, user_pwd, nick_name, remark, err_count, gmt_create)
values (#{id,jdbcType=VARCHAR},
#{user_name,jdbcType=VARCHAR},
#{user_pwd,jdbcType=VARCHAR},
#{nick_name,jdbcType=VARCHAR},
#{remark,jdbcType=VARCHAR},
#{err_count,jdbcType=INTEGER},
#{gmt_create,jdbcType=TIMESTAMP})
</insert>
<update id="update" parameterType="com.inslife.model.Admin">
update admin
set user_name = #{user_name,jdbcType=VARCHAR},
user_pwd = #{user_pwd,jdbcType=VARCHAR},
nick_name = #{nick_name,jdbcType=VARCHAR},
remark = #{remark,jdbcType=VARCHAR},
err_count = #{err_count,jdbcType=INTEGER}
where id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateUserPwd">
update admin
set user_pwd = #{user_pwd,jdbcType=VARCHAR}
where user_name = #{user_name,jdbcType=VARCHAR}
</update>
<update id="updateErrCount">
update admin
set err_count = #{err_count,jdbcType=INTEGER}
where user_name = #{user_name,jdbcType=INTEGER}
</update>
<select id="info" resultMap="BaseResultMap">
select *
from admin
where id = #{id,jdbcType=VARCHAR}
</select>
<delete id="delete">
delete from admin where id = #{id,jdbcType=VARCHAR}
</delete>
<select id="infoByUserName" resultMap="BaseResultMap">
select *
from admin
where user_name = #{user_name,jdbcType=VARCHAR}
</select>
<select id="login" resultMap="BaseResultMap">
select *
from admin
where user_name = #{user_name,jdbcType=VARCHAR}
and user_pwd = #{user_pwd,jdbcType=VARCHAR}
</select>
<select id="listAll" resultMap="BaseResultMap">
select *
from admin
</select> <select id="count" resultType="INTEGER">
select count(1)
from admin
<where>
<if test="keywords != null and keywords != '' ">
and user_name like concat(concat('%',#{keywords,jdbcType=VARCHAR}),'%')
</if>
</where>
</select> <select id="page" resultMap="BaseResultMap">
select *
from admin
<where>
<if test="keywords != null and keywords != '' ">
and user_name like concat(concat('%',#{keywords,jdbcType=VARCHAR}),'%')
</if>
</where>
limit #{offset},#{pageSize}
</select> </mapper>
src/main/java/com/inslife/App.java
package com.inslife; import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication app = new SpringApplication(App.class);
//关闭banner
app.setBannerMode(Banner.Mode.OFF);
app.run(args); System.out.println( "OK" );
}
}
src/main/java/com/inslife/ResUtil.java
package com.inslife.util; import java.util.HashMap;
import java.util.Map; /**
* 输出帮助类
*/
public class ResUtil { public static Map<String,Object> OK(String desc){
return Result("0",desc,null);
}
public static Map<String,Object> OK(String desc,Object data){
return Result("0",desc,data);
} public static Map<String,Object> Error(String desc){
return Result("1",desc,null);
} public static Map<String,Object> Error(String desc,Object data){
return Result("1",desc,data);
} public static Map<String,Object> Result(String code,String desc,Object data){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",code);
map.put("desc",desc);
map.put("data",data);
return map;
}
}
src/main/java/com/model/Admin.java
package com.inslife.model; import java.util.Date; /**
* 管理员信息
*/
public class Admin { private String id;
private String user_name;
private String user_pwd;
private String nick_name;
private String remark;
private Integer err_count;
private Date gmt_create;
private Date gmt_modified; //getter setter public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getUser_name() {
return user_name;
} public void setUser_name(String user_name) {
this.user_name = user_name;
} public String getUser_pwd() {
return user_pwd;
} public void setUser_pwd(String user_pwd) {
this.user_pwd = user_pwd;
} public String getNick_name() {
return nick_name;
} public void setNick_name(String nick_name) {
this.nick_name = nick_name;
} public String getRemark() {
return remark;
} public void setRemark(String remark) {
this.remark = remark;
} public Integer getErr_count() {
return err_count;
} public void setErr_count(Integer err_count) {
this.err_count = err_count;
} public Date getGmt_create() {
return gmt_create;
} public void setGmt_create(Date gmt_create) {
this.gmt_create = gmt_create;
} public Date getGmt_modified() {
return gmt_modified;
} public void setGmt_modified(Date gmt_modified) {
this.gmt_modified = gmt_modified;
}
}
src/main/java/com/mapper/AdminMapper.java
package com.inslife.mapper; import com.inslife.model.Admin;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository; import java.util.List; @Mapper
public interface AdminMapper { /**
* 注解配置
*/
@Select("select * from admin where user_name = #{user_name}")
Admin findByUserName(@Param("user_name") String user_name); /**
* xml配置
*/
int update(Admin admin); /**
* 新增
* @param admin
* @return
*/
int insert(Admin admin); /**
* 更新密码
* @param user_name
* @param user_pwd
* @return
*/
int updateUserPwd(@Param("user_name") String user_name, @Param("user_pwd") String user_pwd); /**
* 更新登录次数
* @param user_name
* @param err_count
* @return
*/
int updateErrCount(@Param("user_name") String user_name, @Param("err_count") Integer err_count); /**
* 通过用户名查询
* @param user_name
* @return
*/
Admin infoByUserName(@Param("user_name") String user_name); /**
* 详细
* @param id
* @return
*/
Admin info(@Param("id") Integer id); /**
* 登录
* @param user_name
* @param user_pwd
* @return
*/
Admin login(@Param("user_name") String user_name, @Param("user_pwd") String user_pwd); /**
* 列出所有
* @return
*/
List<Admin> listAll(); /**
* 统计
* @param keywords
* @return
*/
int count(@Param("keywords") String keywords); /**
* 分页查询
* @param keywords
* @param offset
* @param pageSize
* @return
*/
List<Admin> page(@Param("keywords") String keywords,
@Param("offset") Integer offset,
@Param("pageSize") Integer pageSize);
}
src/main/java/com/controller/IndexController.java
package com.inslife.controller; import com.inslife.mapper.AdminMapper;
import com.inslife.model.Admin;
import com.inslife.util.PageResultObject;
import com.inslife.util.ResUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils; import java.util.List;
import java.util.Date; @Api(value = "用户管理")
@RequestMapping(value = "/api/web")
@RestController
public class AdminController { @Autowired
private AdminMapper adminMapper; @ApiOperation(value = "详细", notes = "详细")
@GetMapping("/admin/{id}")
public Object info(@PathVariable("id") Integer id) {
Admin query = adminMapper.info(id);
return ResUtil.OK("ok", query);
} @ApiOperation(value = "添加", notes = "添加")
@PostMapping("/admin")
public Object insert(@RequestBody Admin admin) {
admin.setId(UUID.randomUUID().toString());
admin.setGmt_create(new Date());
adminMapper.insert(admin);
return ResUtil.OK("ok", admin);
} @ApiOperation(value = "列表", notes = "列表")
@GetMapping("/admin")
public Object listAll() {
List<Admin> data = adminMapper.listAll();
return ResUtil.OK("ok", data);
} @ApiOperation(value = "登录", notes = "登录")
@PostMapping("/login")
public Object login(@RequestBody Admin admin) { if (admin == null || StringUtils.isEmpty(admin.getUser_name()) || StringUtils.isEmpty(admin.getUser_pwd())) {
return ResUtil.Error("用户名或密码为空");
} Admin tryCount = adminMapper.infoByUserName(admin.getUser_name());
if (tryCount != null && tryCount.getErr_count() != null && tryCount.getErr_count() >= 5) {
return ResUtil.Error("登录错误" + tryCount.getErr_count() + "次,用户已被锁定");
} Admin query = adminMapper.login(admin.getUser_name(), admin.getUser_pwd());
if (query == null) {
tryCount = adminMapper.infoByUserName(admin.getUser_name());
if (tryCount != null) {
int count = tryCount.getErr_count() == null ? 0 : tryCount.getErr_count();
count++;
return ResUtil.Error("用户名或密码错误" + count + "次,错误5次后将被锁定");
}
return ResUtil.Error("用户名或密码错误");
} adminMapper.updateErrCount(admin.getUser_name(), 0); return ResUtil.OK("ok", query);
} @ApiOperation(value = "分页", notes = "分页")
@GetMapping("/admin/page")
public Object page(@RequestParam(value = "keywords", required = false) String keywords,
@RequestParam(value = "page_index", required = false) Integer pageIndex,
@RequestParam(value = "page_size", required = false) Integer pageSize) {
if (pageIndex == null || pageIndex <= 0) {
pageIndex = 1;
} if (pageSize == null || pageSize <= 0) {
pageSize = 10;
} int offset = (pageIndex - 1) * pageSize; int count = adminMapper.count(keywords); List<Admin> formList = adminMapper.page(keywords, offset, pageSize); PageResultObject<Admin> pageResultObject = new PageResultObject<Admin>(pageIndex,
pageSize, count, formList); return ResUtil.OK("ok", pageResultObject);
}
}
3.跨域设置
src/main/java/com/config/CorsConfig.java
package com.inslife.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter; /**
* 跨域设置
*/
@Configuration
public class CorsConfig { private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允许任何域名
corsConfiguration.addAllowedHeader("*"); //允许任何头
corsConfiguration.addAllowedMethod("*"); //允许任何方法
return corsConfiguration;
} @Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //注册
return new CorsFilter(source);
} }
4.swagger配置
src/main/java/com/config/Swagger2.java
package com.inslife.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; /**
* swagger生成api说明
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
*
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.inslife.controller"))
.paths(PathSelectors.any())
.build();
} /**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("描述")
.termsOfServiceUrl("https://in-s-life.com")
.contact("admin")
.version("1.0")
.build();
}
}
5.分页辅助类
src/main/java/util/PageResultObject.java
package com.inslife.util; import java.util.ArrayList;
import java.util.List; public class PageResultObject<T> { private Integer page;
private Integer pageSize;
private Integer totalRecords;
private Integer totalPage; private List<T> data; public PageResultObject(Integer page, Integer pageSize, Integer totalRecords, List<T> objects) { if (objects == null) {
objects = new ArrayList<T>();
} if (totalRecords <= 0) {
totalRecords = 0;
} if (page <= 0) {
page = 1;
} if (pageSize <= 0) {
pageSize = 20;
} this.totalPage = (totalRecords % pageSize) > 0 ? (totalRecords / pageSize) + 1 : totalRecords / pageSize; this.data = objects; this.page = page; this.pageSize = pageSize; this.totalRecords = totalRecords;
} public Integer getPage() {
return page;
} public void setPage(Integer page) {
this.page = page;
} public Integer getPageSize() {
return pageSize;
} public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
} public Integer getTotalRecords() {
return totalRecords;
} public void setTotalRecords(Integer totalRecords) {
this.totalRecords = totalRecords;
} public Integer getTotalPage() {
return totalPage;
} public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
} public List<T> getData() {
return data;
} public void setData(List<T> data) {
this.data = data;
}
}
6.运行项目即可实现基本的用户管理功能
SpringBoot 使用Mybatis操作mysql示例的更多相关文章
- kotlin + springboot整合mybatis操作mysql数据库及单元测试
项目mybatis操作数据库参考: http://how2j.cn/k/springboot/springboot-mybatis/1649.html?p=78908 junit对controller ...
- Spring Boot(六)集成 MyBatis 操作 MySQL 8
一.简介 1.1 MyBatis介绍 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集. ...
- SpringBoot 集成Mybatis 连接Mysql数据库
记录SpringBoot 集成Mybatis 连接数据库 防止后面忘记 1.添加Mybatis和Mysql依赖 <dependency> <groupId>org.mybati ...
- springboot整合mybatis连接mysql数据库出现SQLException异常
在springboot整合mybatis连接数据库的时候,项目中遇到一个SQLException,我检查了properties配置文件,看数据源有没有配错,检查有没有打错字,在数据库中把sql语句查询 ...
- JAVA-ORM框架整理➣Mybatis操作MySQL
概述 在Java中,对数据库操作的框架很多,上节概述Hibernate的简单使用,这里简单整理Mybatis的使用.Mybatis也是简单的数据库操作框架,通过IOC方式,获取操作类对象,进行数据的操 ...
- springboot学习-springboot使用spring-data-jpa操作MySQL数据库
我们在上一篇搭建了一个简单的springboot应用,这一篇将介绍使用spring-data-jpa操作数据库. 新建一个MySQL数据库,这里数据库名为springboot,建立user_info数 ...
- 尚硅谷springboot学习30-docker安装mysql示例
docker pull mysql 错误的启动示例 错误日志:需要设置密码 正确的启动 但还不能直接使用,因为没有做端口映射,外界无法连接 可用的启动 连接成功 几个高级的操作 指定配置文件 dock ...
- Mybatis操作Mysql批量更新的一个坑-&allowMultiQueries=true允许批量更新
前言 利用Mybatis批量更新或者批量插入,实际上即使Mybatis完美支持你的sql,你也得看看你操作的数据库是否完全支持,而同事,最近就遇到这样的一个坑! 问题 先带大家来 ...
- SpringBoot 整合 Mybatis 和 Mysql (详细版)
结构如下 1.引入相关依赖 <!--mysql--><dependency> <groupId>mysql</groupId> <artifact ...
随机推荐
- Win7安装VS2019
SP1 补丁 WIN7安装VS2019需要更新两个补丁才能顺利安装,否则会闪退. KB4474419 KB4490628 https://zhidao.baidu.com/question/18026 ...
- 微信公众号开发不能使用session原因
今天做微信公众号开发整合功能的时候,使用session保存记录.用postman测试好使,但是一旦用手机就不好使.上网查了好久才明白,微信开发是不能用session的.具体原因如下:因为微信的所有请求 ...
- PHP四种基本排序
1. 冒泡排序 // 1.冒泡排序法 $array = [12,3,23,2,4,1,0]; function maoPao($arr){ //先判断是不是空数组 if(!empty($arr)){ ...
- Java web 简单的增删改查程序(超详细)
就是简单的对数据进行增删改查.代码如下: 1.bean层:用来封装属性及其get set方法 toString方法,有参构造方法,无参构造方法等. public class Bean { privat ...
- Dell PowerEdge服务器RAID卡驱动下载
Dell PowerEdge服务器RAID卡驱动下载 DELL新阵列卡驱动下载 型号 支持系统驱动 H310/710 /710P/810 Win2008 x32 Windows 2008 x64 Wi ...
- 认识并安装RabbitMQ(以Windows系统为例)
一.初识RabbitMQ 百度百科有这么一句话: MQ是消费-生产者模型的一个典型的代表,一端往消息队列中不断写入消息, 而另一端则可以读取或者订阅队列中的消息. MQ和JMS类似,但不同的是JMS是 ...
- log4j 多进程配置要注意的
多进程写日志文件 方法一: 解决log4j公用配置文件,多进程同时写同一个log文件,因存在操作系统pv操作问题, 导致部分日志丢失.解决方案是不同的进程写不同的log文件 测试于:Log4j 1.2 ...
- flask 第四篇 模板语言jinja2
是时候开始写个前端了,Flask中默认的模板语言是Jinja2 现在我们来一步一步的学习一下 Jinja2 捎带手把 render_template 中留下的疑问解决一下 首先我们要在后端定义几个字符 ...
- JSP自定义标签的执行原理
当浏览器发来请求后,会将这个请求交给JSP翻译成的servlet来处理,自定义标签对应servlet中一个方法的调用,这个方法主要步骤如下 1,产生标签处理类的实例对象 2,将pageContext传 ...
- CSS标签详解
CSS3标签 Css3概述 从2010年开始,HTML5与CSS3就一直是互联网技术中最受关注的两个话题.从前端技术的角度可以把互联网的发展分为三个阶段:第一阶段是web1.0以内容为主的网络,前端主 ...