今天学习了springboot整合mybatis写了一套增删改查准备工作如下
我使用的是idea。
1、建立一个sprignboot项目
无需其他操作,选中后直接下一步
注:jdk必须为1.8。
2、同样也还是直接点下一步
Group:项目会自动生成在java文件夹的的文件夹(可以自己自定义)
Artifact:工作空间的名字(可以自己定义)
3、是springboot的灵魂所在
选中你开发所需要的依赖
首先是sprintboot的版本:一般不用自己手动选择,idea会自动进行大数据选择
在下面只解释我使用的勾选
Core:springboot核心
DevTools:热部署
Lombok:自动生成构造方法
Web:网页
Web:网页开发
Template Engines:模板引擎
Thymeleaf:很好用,自己百度了解
SQL:数据库
mysql:mysql数据库
jdbc:数据库连接方式
mybatis:有利于sql语句的便捷开发
选完之后在右侧就会出现以下视图,确定选完之后就下一步
4、建立项目:finish,记得一定要联网,以便导入依赖
5、可以在pom文件中看到前面勾选的依赖,原理是基于maven继承的方式实现的
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
com.wen
stumgr
0.0.1-SNAPSHOT
stumgr
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
mysql
mysql-connector-java
8.0.15
com.github.pagehelper
pagehelper
5.1.6
com.github.pagehelper
pagehelper-spring-boot-autoconfigure
1.2.5
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
src/main/java
**/*.xml
src/main/resources
6、项目文件夹的结构,public下的html为项目起始页
7、给maven 的settings.xml配置文件的profiles标签添加,用来指定jdk版本
jdk-1.8
true
1.8
1.8
1.8
1.8
8、springboot的主程序;用来启动spring boot引用,这里会自动生成
springboot是以纯java的方式启动,自带服务器,所以无需配置服务器
切记:主程序文件不能放到任何包中,不然项目将无法找到主程序导致无法启动
@SpringBootApplication: Spring Boot应用标注在某个类上说明这个类是SpringBoot的主配置类
SpringBoot就应该运行这个类的main方法来启动SpringBoot应用;
/* SparingBoot启动类 */
@SpringBootApplication//这行注解得作用,表示这是一个springboot的应用程序
@MapperScan("com.wen.stumgr.mapper")//扫描mapper文件mapper相当于dao层
public class StumgrApplication {
public static void main(String[] args) {
SpringApplication.run(StumgrApplication.class, args);
}
}
8、配置application.properties,在后面可以改使用为application.yml,在这里两种都会写
切记application有两种可以自定义使用,但这个文件的名字是固定的不能随便修改
因为选择了jdbc连接方式所以必须配置驱动以及连接地址、用户名、密码
不然项目无法启动会报错
application.properties的基本配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/studentdb?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&zeroDateTimeBehavior=CONVERT_TO_NULL
spring.datasource.username=root
spring.datasource.password=root
##给实体类起别名,为了方便mybatis在xml文件中设置返回值
mybatis.type-aliases-package=com.wen.stumgr.pojo
application.yml的基本配置
##日志打印,配置完日志文件后控制台可以看到打印sql语句,很有用,方便查看自己sql语句是否有错
logging:
level:
com.changan.stumgr.mapper.*: debug
#公共配置与profiles选择无关
mybatis:
typeAliasesPackage: com.changan.stumgr.pojo
mapperLocations: classpath:mapper/*.xml
##数据库连接的配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/studentdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
##分页插件的配置
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
##当端口占用时可以修改端口号
server:
port: 8080
9、controller层
package com.wen.stumgr.controller;
import com.github.pagehelper.PageInfo;
import com.wen.stumgr.pojo.Student;
import com.wen.stumgr.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
//@RestController 返回json格式
@Controller//表明这是一个控制层
public class StudentController {
@Autowired
private StudentService studentService;
/**
* 视图解析器
* @return 一个视图名称 /templates/*。html
*/
@GetMapping("/students")
public String list(Integer pageNum,Model model){
//ctrl+F9 实现热部署
PageInfo pageInfo = studentService.selAllStudent(pageNum);
model.addAttribute("pageInfo",pageInfo);
return "list";
}
@RequestMapping("/student/{id}")
public String delete(@PathVariable("id") Integer id){
System.out.println(id+"------");
studentService.del(id);
return "redirect:/students";
}
@RequestMapping("/edit")
public String edit(Integer id , Model model){
if(id!=null){//说明执行修改操作
Student student = studentService.findSrudentById(id);
model.addAttribute("student",student);
}
return "edit";
}
@RequestMapping("/add")
public String add(Student student){
studentService.addStudent(student);
return "redirect:/students";
}
@RequestMapping("/upd")
public String upd(Student student){
studentService.updateStudent(student);
return "redirect:/students";
}
}
10、mapper层
StudentMapper
package com.wen.stumgr.mapper;
import com.wen.stumgr.pojo.Student;
import org.apache.ibatis.annotations.*;
import org.mybatis.spring.annotation.MapperScan;
import java.util.List;
@Mapper
public interface StudentMapper {
//@Select("select * from Student")
List selAllStudent();
@Insert("INSERT INTO `student`(`id`, `name`, `sex`, `gradeId`) " +
"VALUES (null, #{name}, #{sex}, #{gradeId});")
int addStudent(Student student);
@Delete("delete from student where id = #{id}")
int del (int id);
@Update("UPDATE `student` SET `name` = #{name}, `sex` = #{sex}, `gradeId` = #{gradeId} WHERE `id` = #{id};")
int updateStudent();
@Select("select * from student where id = #{id}")
Student findSrudentById(Integer id);
}
StudentMapper.xml
11、pojo层
Student
package com.wen.stumgr.pojo;
/**
* student
*
* @author yunfa_liu
* @version 1.0.0 2019-05-14
*/
public class Student {
/** 版本号 */
private static final long serialVersionUID = -9166764575082064858L;
/** id */
private Integer id;
/** name */
private String name;
/** sex */
private String sex;
/** gradeId */
private Integer gradeId;
/** 省的映射了,两表联查 */
private Grade grade;
/**
* 获取Grade实体类对象
*
* @return id
*/
public Grade getGrade() {
return grade;
}
/**
* 设置Grade实体类对象
*
* @return id
*/
public void setGrade(Grade grade) {
this.grade = grade;
}
/**
* 获取id
*
* @return id
*/
public Integer getId() {
return this.id;
}
/**
* 设置id
*
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取name
*
* @return name
*/
public String getName() {
return this.name;
}
/**
* 设置name
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取sex
*
* @return sex
*/
public String getSex() {
return this.sex;
}
/**
* 设置sex
*
* @param sex
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* 获取gradeId
*
* @return gradeId
*/
public Integer getGradeId() {
return this.gradeId;
}
/**
* 设置gradeId
*
* @param gradeId
*/
public void setGradeId(Integer gradeId) {
this.gradeId = gradeId;
}
}
使用插件的另一种方式,但要先导入插件,点击Search in repositonries
选中lombok插件,点击install,下载插件,确保自己有网
这样之后的实体类代码
package com.wen.stumgr.pojo;
import lombok.Data;
/**
* student
*
* @author yunfa_liu
* @version 1.0.0 2019-05-14
*/
@Data//便捷产生getset方法
public class Student {
/** id */
private Integer id;
/** name */
private String name;
/** sex */
private String sex;
/** gradeId */
private Integer gradeId;
}
12、service层
StudentService
package com.wen.stumgr.service;
import com.github.pagehelper.PageInfo;
import com.wen.stumgr.pojo.Student;
import java.util.List;
public interface StudentService {
PageInfo selAllStudent(Integer pageNum);
int addStudent(Student student);
int del (int id);
int updateStudent(Student student);
Student findSrudentById(Integer id);
}
StudentServiceimpl
package com.wen.stumgr.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wen.stumgr.mapper.StudentMapper;
import com.wen.stumgr.pojo.Student;
import com.wen.stumgr.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceimpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public PageInfo selAllStudent(Integer pageNum) {
//pageNum 当前的页码 pageSize:每页显示的条数
if(pageNum==null){//刚开始请求的时候默认为1
pageNum = 1;
}
PageHelper.startPage(pageNum,2);
List students = studentMapper.selAllStudent();
PageInfo pageInfo = new PageInfo<>(students);
return pageInfo;
}
@Override
public int addStudent(Student student) {
return studentMapper.addStudent(student);
}
@Override
public int del(int id) {
return studentMapper.del(id);
}
@Override
public int updateStudent(Student student) {
return studentMapper.updateStudent();
}
@Override
public Student findSrudentById(Integer id) {
return studentMapper.findSrudentById(id);
}
}
13、两个html页面
list.html
edit.html
Title
14、数据库
student表
/*
Navicat Premium Data Transfer
Source Server : root
Source Server Type : MySQL
Source Server Version : 50724
Source Host : localhost:3306
Source Schema : test
Target Server Type : MySQL
Target Server Version : 50724
File Encoding : 65001
Date: 16/05/2019 21:18:56
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`sex` char(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`gradeId` int(4) NOT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `FK_STU`(`gradeId`) USING BTREE,
CONSTRAINT `FK_STU` FOREIGN KEY (`gradeId`) REFERENCES `grade` (`gradeid`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 25 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (5, '周佳惠', '女', 2);
INSERT INTO `student` VALUES (7, '聂长安', '男', 3);
INSERT INTO `student` VALUES (9, '小慧', '女', 3);
INSERT INTO `student` VALUES (10, '李豪', '男', 3);
INSERT INTO `student` VALUES (23, '罗英姿', '雄', 1);
INSERT INTO `student` VALUES (24, '卜思聪', '雌', 3);
SET FOREIGN_KEY_CHECKS = 1;
最后是我项目的结构图