前言:
1、(SprigBoot整合SpringMVC+Mybatis)
2、以thymeleaf作为视图层技术整合
3、springboot版本2.0.5.RELEASE

创建项目
1、添加依赖及启动器

 <dependencies><!--springboot web 启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--thymeleaf 启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!-- &lt;!&ndash; Oracle数据库驱动 &ndash;&gt;<dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>11.2.0.3</version></dependency>--><!--Mybatis 依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><!-- mysql 数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--  单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><!-- mybatis generator 自动生成代码插件 --><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.2</version><configuration><configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile><overwrite>true</overwrite><verbose>true</verbose></configuration></plugin></plugins></build>

2、添加application.yml全局配置文件

#服务器端口
server:port: 8082
#mybatis mapper映射文件和扫描实体类配置文件     位置
mybatis:config-location: classpath:/mybatis/config/mybatis-config.xmlmapper-locations: classpath:/mybatis/mapper/*.xml
#mysql数据库驱动 url username  password
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=trueusername: rootpassword: root

mybatis-config.xml:mybatis配置文件
存放此文件位置:src/main/resource/mybatis/config
如果,没有创建即可!!!

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings><typeAliases><package name="com.gblfy.entity"/></typeAliases>
</configuration>

3、数据库表设计 创建数据库test,新建user表

CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',`age` int(11) DEFAULT NULL COMMENT '年龄',`password` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '密码',`sex` int(11) DEFAULT NULL COMMENT '性别',`username` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '用户名',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;


一、添加用户

需求实现流程:

  • 1、用户在页面上输入用户信息
  • 2、点击确认按钮,保存用户数据

前端用户信息输入页面->>>确认按钮(提交action跳转相应操作成功/失败页面)

  • 2.1 新建包
在src/main/java目录下建包:
com.gblfy.controller :存放前端控制器
com.gblfy.entity :实体类
com.gblfy.repository:mapper接口
com.gblfy.service:服务接口
com.gblfy.service.impl:服务实现类
在src/main/resources目录下dir(目录):

创建以下几个目录:

mybatis/mapper:存放mapper接口的映射文件
mybatis/config:存放mybatis的配置文件(扫描实体类)
  • 2.2 创建实体类User:

为了清楚观看数据,已重写toString方法

@Data
public class User implements Serializable {private Integer id;private Integer age;private String password;private Integer sex;private String username;private static final long serialVersionUID = 1L;
}

2.2 创建mapper接口及mapper映射文件

public interface UserMapper {int insert(User record);
}

2.2.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="com.gblfy.repository.UserMapper" ><resultMap id="BaseResultMap" type="com.gblfy.entity.User" ><id column="id" property="id" jdbcType="INTEGER" /><result column="age" property="age" jdbcType="INTEGER" /><result column="password" property="password" jdbcType="VARCHAR" /><result column="sex" property="sex" jdbcType="INTEGER" /><result column="username" property="username" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, age, password, sex, username</sql>
</mapper>

2.2.2 添加用户部分

<insert id="insert" parameterType="com.gblfy.springboot.chapter2.entity.User" >insert into user (id, age, password, sex, username)values (#{id,jdbcType=INTEGER}, #{age,jdbcType=INTEGER}, #{password,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR})</insert>

2.3 创建service接口及实现类

public interface UserService {/*** 新增用户** @param record* @return*/int insert(User record);
}

实现类

@Service
@Transactional//事物
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper usersMapper;@Overridepublic int insert(User user) {return usersMapper.insert(user);}
}

2.4 新建controller

方法showPage:用于做页面跳转
这样就可以访问templates目录下的静态Html文件
templates:默认是安全的、外界无访问权限
/*** @author gblfy* @ClassNme UsersController* @Description 用户在页面上,添加数据,后台保存,视图技术采用thymeleaf* @Date 2019/2/22 18:35* @version1.0*/
@Controller//页面跳转不用@ResponseBody 只处理返回数据json
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;/*** 跳转页面** @param page* @return*/@RequestMapping("/{page}")public String showPage(@PathVariable String page) {return page;}/*** 添加用户** @param user* @return*/@RequestMapping("/addUser")public String save(User user) {userService.insert(user);return "ok";}
}
  • 2.5 页面
前端信息输入页面:
此页面通过前端控制层方法showPage跳转
,因此,此页面输入url就可以直接在浏览器上访问
在resources/templates目录下面创建input.html:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Thymeleaf-用户添加数据页面</title>
</head>
<body><form th:action="@{/user/addUser}" method="post">姓名:<input type="text" name="username"/><br/>口令:<input type="text" name="password"/><br/>年龄:<input type="text" name="age"/><br/>性别:<input type="text" name="sex"/><br/><input type="submit" value="确认"/><br/></form>
</body>
</html>

链接:http://localhost:8082/user/input
效果图:

点击页面中的确认按钮即可跳转到url 和/user/addUser绑定的对应方法上,

触发这个方法之后,通过调用userService接口中的insert方法把user信息对象当做参数传到业务处理层

在业务处理层,通过调用mapper接口,mapper接口和mapper映射文件,与数据库进行交互
操作成功页面:
如果点击确认插入数据库用户数据成功,就会跳转操作成功页面
在resources/templates目录下面创建ok.html:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>操作提示页面</title>
</head>
<body>操作成功!!!
</body>
</html>

二、查询所用用户信息

2.1 mapper映射文件:

<select id="selectAll" resultMap="BaseResultMap" >select<include refid="Base_Column_List"/>from user
</select>

2.2 mapper接口

public interface UserMapper {/*** 查询所有用户信息** @return*/List<User> selectAll();
}

2.3 服务接口

public interface UserService {/*** 查询所有用户信息* @return*/List<User> selectAll();
}

2.4 服务实现类

@Service
@Transactional//事物
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper usersMapper;
@Override
public List<User> selectAll() {return usersMapper.selectAll();}
}

2.5 controller层


/*** @author gblfy* @ClassNme UsersController* @Description 用户在页面上,添加数据,后台保存,视图技术采用thymeleaf* @Date 2019/2/22 18:35* @version1.0*/
@Controller//页面跳转不用@ResponseBody 只处理返回数据json
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;/*** 跳转页面** @param page* @return*/@RequestMapping("/{page}")public String showPage(@PathVariable String page) {return page;}
/*** 查询全部用户** @param model* @return*/
@RequestMapping("/findUserAll")
public String findUserAll(Model model) {List<User> list = userService.selectAll();model.addAttribute("list", list);return "showUser";}
}

当页面访问:localhost:8080/user/findUserAll时,会触发findUserAll这个方法,先去调用userService接口中的selectAll方法与持久层交互完成用户信息的查询,将查询的结果返回到控制层,通过Model将数据传到页面,进行显示。会跳转到showUser.html页面上,利用thymeleaf视图技术,将用户互信息显示。

三、通过id查询用户

3.1 mapper映射文件:

select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from userwhere id = #{id,jdbcType=INTEGER}
</select>

3.2 mapper接口

User selectByPrimaryKey(Integer id);

3.3 服务接口

/*** 根据id查询** @param id* @return*/
User selectByPrimaryKey(Integer id);

3.4 服务实现类

@Override
public User selectByPrimaryKey(Integer id) {return usersMapper.selectByPrimaryKey(id);
}

3.5 控制层

/*** 通过id查询用户** @param id* @return*/
@RequestMapping("/findUserById")
public String findUserById(Integer id, Model model) {User user = userService.selectByPrimaryKey(id);model.addAttribute("user", user);return "updateUser";
}

3.6 前端显示页面:showUser.html

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>操作提示页面</title>
</head>
<body><table border="1" style="width: 600px"><tr><th>用户id</th><th>用户姓名</th><th>口令</th><th>年龄</th><th>性别</th><th>更新操作</th><th>删除操作</th></tr><tr th:each="user : ${list}"><td th:text="${user.id}"></td><td th:text="${user.username}"></td><td th:text="${user.password}"></td><td th:text="${user.age}"></td><td th:text="${user.sex}"></td><td><a th:href="@{/user/findUserById(id=${user.id})}">更新用户</a></td><td><a th:href="@{/user/delUser(id=${user.id})}">删除用户</a></td></tr></table>
</body>
</html>


在前端显示页面点击更新用户(任选一个),就可以吧用户id传递过去

这是一种页面跳转的方式

也可以直接在url后面修改id,进行查询,是一样的效果

四、编辑用户信息

4.1 mapper映射文件

<update id="updateByPrimaryKey" parameterType="com.gblfy.entity.User" >update userset age = #{age,jdbcType=INTEGER},password = #{password,jdbcType=VARCHAR},sex = #{sex,jdbcType=INTEGER},username = #{username,jdbcType=VARCHAR}where id = #{id,jdbcType=INTEGER}
</update>

4.2 mapper接口

User selectByPrimaryKey(Integer id);

4.3 服务接口

/*** 更新用户信息** @param record* @return*/
void updateByPrimaryKey(User record);

4.4 服务实现类

@Override
public void updateByPrimaryKey(User record) {usersMapper.updateByPrimaryKey(record);
}

4.5控制层

/*** 编辑用户信息** @param user* @return*/
@RequestMapping("/editUser")
public String findUserById(User user) {userService.updateByPrimaryKey(user);return "ok";
}

在前端页面点击更新用户操作,就会把需要更新的用户id传递过去



点击确认按钮,提交

数据库查看:

五、通过id删除用户信息

5.1 mapper映射文件:

<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >delete from userwhere id = #{id,jdbcType=INTEGER}
</delete>

5.2 mapper接口

void deleteByPrimaryKey(Integer id);

5.3 服务接口

/*** 根据id删除** @param id* @return*/
void deleteByPrimaryKey(Integer id);

5.4 服务实现类

@Override
public void deleteByPrimaryKey(Integer id) {usersMapper.deleteByPrimaryKey(id);
}

5.5 控制层

/*** 删除用户** @param id* @return*/
@RequestMapping("/delUser")
public String findUserById(Integer id) {userService.deleteByPrimaryKey(id);return "redirect:/user/findUserAll";
}

在前端页面上点击删除用户操作,就会把需要删除的用户id传递过去,然后,根据用户id将和用户id相对应的用户信息删除,最后,重定向到删除页面,观察结果。

本文源码下载:

github地址:
https://github.com/gb-heima/Spring-Boot-Actual-Combat/tree/master/parent/spring-boot-chapter-10

第十篇:Spring Boot整合mybatis+Mysql 入门试炼02相关推荐

  1. Spring Boot 教程(三): Spring Boot 整合Mybatis

    教程简介 本项目内容为Spring Boot教程样例.目的是通过学习本系列教程,读者可以从0到1掌握spring boot的知识,并且可以运用到项目中.如您觉得该项目对您有用,欢迎点击收藏和点赞按钮, ...

  2. Spring boot 整合 Mybatis 实现增删改查(MyEclipse版)

    1.首先搭建好一个Spring boot 程序,编写好启动类. 启动类代码如下: @SpringBootApplication public class Start {public static vo ...

  3. spring boot整合mybatis+通用mapper+pagehelper分页插件

    spring boot整合mybatis+通用mapper+pagehelper分页插件 pom依赖 <?xml version="1.0" encoding="U ...

  4. spring boot整合mybatis步骤

    spring boot整合mybatis步骤 官方说明:MyBatis-Spring-Boot-Starter will help you use MyBatis with Spring Boot 其 ...

  5. Spring Boot整合MyBatis

    最近项目原因可能会继续开始使用MyBatis,已经习惯于spring-data的风格,再回头看xml的映射配置总觉得不是特别舒服,接口定义与映射离散在不同文件中,使得阅读起来并不是特别方便. Spri ...

  6. Spring Boot 整合MyBatis(23)

    Spring Boot 整合MyBatis Spring Boot 整合 Druid 引入依赖 配置 application.yml pring Boot 整合 tk.mybatis 引入依赖 配置 ...

  7. Spring Boot 整合 MyBatis Plus实现多数据源的两种方式

    第一种:使用配置类的方式: 项目结构 xml依赖: <?xml version="1.0" encoding="UTF-8"?> <proje ...

  8. 干货必看|Spring Boot整合MyBatis框架详解

    在开发中,我们通常会对数据库的数据进行操作,Sprirng Boot对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持.所以今天壹哥就给大家讲解一下,如何在SpringBoot环境中整合 ...

  9. Spring Boot整合Mybatis【超详细】

    pring Boot整合Mybatis 配置文件形式 pom.xml 配置数据源 UserMapper.xml UserMapper 配置springboot整合mybatis 在运行类上添加@Map ...

最新文章

  1. oracle查看用户密码时间限制
  2. python程序设计之文件_Python程序设计之文件操作(2)
  3. 有名管道和无名管道的区别
  4. vs用c语言写贪吃蛇,熬书几个月,终于编出简易的贪吃蛇了,VS2013
  5. python 折线图中文乱码_彻底解决 Python画图中文乱码问题--Pyplotz组件
  6. 【Tensorflow】tf.nn.depthwise_conv2d如何实现深度卷积?+深度可分离卷积详解
  7. NandFlash启动理解(S3C2410)
  8. SSO单点登录学习总结(3)—— 基于CAS实现单点登录实例
  9. 项目团队管理 Atitit 职位的自动分配草案 attilax总结
  10. ENVI完整安装步骤
  11. 转载:在Python 3中使用深度森林(Deep Forest)进行分类
  12. 秋招/校招面试不完全整理
  13. 金标股份冲刺A股上市:计划募资约6亿元,许光荣为董事长
  14. 全球及中国板材制造行业销售前景与产销规模分析报告2022-2028年
  15. 极品特效HTML5动画推荐,不看的程序员后悔一辈子
  16. 方框滤波(Box filtering)
  17. 芯盾时代: 开启“智慧身份认证”新时代
  18. STM32外部中断触发
  19. 在Centos8上安装漏洞扫描软件Nessus
  20. 怎样找自己研究领域的论文

热门文章

  1. python中的[-1]、[:-1]、[::-1]、[n::-1]
  2. California Fault Lines: Understanding the Causes and Impact of Network Failures
  3. Mr. Bender and Square
  4. KMP 深度讲解next数组的求解
  5. 历经7年双11实战,阿里巴巴是如何定义云原生混部调度优先级及服务质量的?
  6. Cloudera CDP 企业数据云测试开通指导
  7. 基于https国密算法构建安全数据传输链路
  8. 阿里云推出全新内存增强型实例re6,性能提升30%
  9. 快速入门容器服务,创建Kubernetes集群
  10. 标记 (TAG) 您的 k8s 集群资源