
??博客主页:??
欢迎关注:??点赞??收藏留言
系列专栏:SSM框架整合专栏
如果觉得博主的文章还不错的话,请三连支持一下博主。
??欢迎大佬指正,一起 学习!一起加油!

创建好项目之后,可根据自己的编程习惯,进行下一步。

4.0.0
com.jkj
ssm
1.0-SNAPSHOT
war
org.springframework
spring-webmvc
5.2.10.RELEASE
org.springframework
spring-jdbc
5.2.10.RELEASE
org.springframework
spring-test
5.2.10.RELEASE
org.mybatis
mybatis
3.5.6
org.mybatis
mybatis-spring
1.3.0
mysql
mysql-connector-java
5.1.47
com.alibaba
druid
1.1.16
junit
junit
4.12
test
javax.servlet
javax.servlet-api
3.1.0
provided
com.fasterxml.jackson.core
jackson-databind
2.9.0
org.testng
testng
RELEASE
compile
junit
junit
4.12
compile
org.slf4j
slf4j-log4j12
1.7.21
test
SpringConfig配置类
@Configuration
@ComponentScan
package com.jkj.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan({“com.jkj.service”})
public class SpringConfig {
}
resources编写jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springboot
jdbc.username=root
jdbc.password=root
JdbcConfig的配置类
@Bean
@Value
package com.jkj.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class JdbcConfig {
@Value(“
j
d
b
c
.
d
r
i
v
e
r
"
)
p
r
i
v
a
t
e
S
t
r
i
n
g
d
r
i
v
e
r
;
@
V
a
l
u
e
(
"
{jdbc.driver}") private String driver; @Value("
jdbc.driver")privateStringdriver;@Value("{jdbc.url}”)
private String url;
@Value(“
j
d
b
c
.
u
s
e
r
n
a
m
e
"
)
p
r
i
v
a
t
e
S
t
r
i
n
g
u
s
e
r
n
a
m
e
;
@
V
a
l
u
e
(
"
{jdbc.username}") private String username; @Value("
jdbc.username")privateStringusername;@Value("{jdbc.password}”)
private String password;
@Bean
public DataSource datasource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setDriverClassName(driver);
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
return datasource;
}
}
MyBatisConfig配置类
SqlSessionFactory是MyBatis的核心对象,用于初始化MyBatis,读取配置文件,创建SqlSession对象,SqlSession使用JDBC方式与数据库交互,也提供了数据表的增删改查方法。
第一个@Bean
第二个@Bean
package com.jkj.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
@Bean //创建sqlSessionFactory对象
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource) ;
factoryBean.setTypeAliasesPackage( "com.jkj.domain");
return factoryBean;
}
@Bean //创建数据源对象
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage( "com.jkj.dao" ) ;
return msc;
}
}
SpringMvcConfig配置类
@EnableWebMvc
package com.jkj.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan({“com.jkj.controller”})
@EnableWebMvc
public class SpringMvcConfig {
}
Web项目入口ControllerConfig配置类
getRootConfigClasses加载的是Spring的核心配置
getServletConfigClasses加载的是SpringMVC的核心配置
getServletMappings就是定义SpringMVC要拦截的请求
package com.jkj.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class ControllerConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
//加载Spring配置类
@Override
protected Class>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } //加载SpringMvc配置类 @Override protected Class>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
//设置SpringMVC请求地址拦截规则
@Override
protected String[] getServletMappings() {
return new String[]{“/”};
}
//设置post请求中文乱码过滤器
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(“utf-8”);
return new Filter[]{filter};
}
}
SpringConfig配置类
@PropertySource
classpath
value
@Import
@EnableTransactionManagement
package com.jkj.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan({“com.jkj.service”})
@PropertySource(“classpath:jdbc.properties”)
@Import({JdbcConfig.class,MyBatisConfig.class})
public class SpringConfig {
}
tbl_book表

往表里插入数据

package com.jkj.domain;
public class Book {
private Integer id;
private String name;
private String type;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + ''' +
", type='" + type + ''' +
", description='" + description + ''' +
'}';
}
}
实体类也可以用注解形式
需要导入lombok依赖
@Data
package com.jkj.domain;
import lombok.Data;
@Data
public class Book {
private Integer id;
private String name;
private String type;
private String description;
}
有时在项目中,执行一些相对简单的SQL语句时,使用Mybatis的相关注解在Dao层的直接使用注解实现
@Select@Insert@Update@Deletepackage com.jkj.dao;
import com.jkj.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface BookDao {
@Insert(“insert into tbl_book values(null,#{type},#{name},#{description})”)
public int save(Book book);
@Update(“update tbl_book set type=#{type},name=#{name},description=#{description}”)
public int update(Book book);
@Delete(“delete from tbl_book where id=#{id}”)
public int delete(Integer id);
@Select(“select * from tbl_book where id=#{id}”)
public Book getById(Integer id);
@Select(“select * from tbl_book”)
public List getAll();
}
package com.jkj.service;
import com.jkj.domain.Book;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface BookService {
/**
*保存
* @param book
* @return
*/
public Boolean save(Book book);
/**
*修改
* @param book
* @return
*/
public Boolean update(Book book);
/**
*删除
* @param id
* @return
*/
public Boolean delete(Integer id);
/**
*id查询
* @param id
* @return
*/
public Book getById(Integer id);
/**
* 查询全部
* @return
*/
public List getAll();
}
@Service
@Autowired
package com.jkj.service.impl;
import com.jkj.controller.Code;
import com.jkj.dao.BookDao;
import com.jkj.domain.Book;
import com.jkj.excption.BusinessException;
import com.jkj.service.BookService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public Boolean save(Book book) {
bookDao.save(book);
return true;
}
@Override
public Boolean update(Book book) {
bookDao.update(book);
return true;
}
@Override
public Boolean delete(Insert id) {
bookDao.delete(id);
return true;
}
@Override
public Book getById(Integer id) {
return bookDao.getById(id);
}
@Override
public List getAll() {
return bookDao.getAll();
}
}
@RestController
@RequestMapping
@PathVariable
@RequestBody@RequestParam @Pathvariable区别
区别
应用
@XXXMapping
package com.jkj.controller;
import com.jkj.domain.Book;
import com.jkj.service.BookService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(“/books”)
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@PutMapping
public Boolean update(@RequestBody Book book) {
return bookService.update(book);
}
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Insert id) {
return bookService.delete(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}
@GetMapping
public List getAll() {
return bookService.getAll();
}
@RunWith就是一个运行器
@RunWith(JUnit4.class)就是指用JUnit4来运行
@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
@ContextConfiguration
@Autowired
package com.jkj.test;
import com.jkj.config.SpringConfig;
import com.jkj.domain.Book;
import com.jkj.service.BookService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookTest {
@Autowired
private BookService bookService;
@Test
public void getById(){
Book byId = bookService.getById(7);
System.out.println(byId);
}
@Test
public void getAll(){
List all = bookService.getAll();
for (Book book : all) {
System.out.println(book);
}
}
}
测试结果:


新增,修改,删除需要在PostMan软件中测试,在这就不过多叙述,详细步骤在Springboot专栏里。
开启注解式事务驱动
@EnableTransactionManagement
package com.jkj.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan({“com.jkj.service”})
@PropertySource(“classpath:jdbc.properties”)
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
配置事务的管理器
事务管理器控制事务时需要使用数据源对象,需要配置在JdbcConfig中
package com.jkj.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class JdbcConfig {
@Value(“
j
d
b
c
.
d
r
i
v
e
r
"
)
p
r
i
v
a
t
e
S
t
r
i
n
g
d
r
i
v
e
r
;
@
V
a
l
u
e
(
"
{jdbc.driver}") private String driver; @Value("
jdbc.driver")privateStringdriver;@Value("{jdbc.url}”)
private String url;
@Value(“
j
d
b
c
.
u
s
e
r
n
a
m
e
"
)
p
r
i
v
a
t
e
S
t
r
i
n
g
u
s
e
r
n
a
m
e
;
@
V
a
l
u
e
(
"
{jdbc.username}") private String username; @Value("
jdbc.username")privateStringusername;@Value("{jdbc.password}”)
private String password;
@Bean
public DataSource datasource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setDriverClassName(driver);
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
return datasource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
添加事务
@Transactional
package com.jkj.service;
import com.jkj.domain.Book;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface BookService {
/**
*
* @param book
* @return
*/
public Boolean save(Book book);
/**
*
* @param book
* @return
*/
public Boolean update(Book book);
/**
*
* @param id
* @return
*/
public Boolean delete(Integer id);
/**
*
* @param id
* @return
*/
public Book getById(Integer id);
/**
*
* @return
*/
public List getAll();
}
创建Result类,放在controller包下,可以不写toString方法,因为最后会被被转为json格式,getter和setter方法要写。
public class Result {
//描述统一格式中的数据
private Object data;
//描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
private Integer code;
//描述统一格式中的消息,可选属性
private String msg;
public Result() {
}
//构造方法是方便对象的创建
public Result(Integer code,Object data) {
this.data = data;
this.code = code;
}
//构造方法是方便对象的创建
public Result(Integer code, Object data, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "Result{" +
"data=" + data +
", code=" + code +
", msg='" + msg + ''' +
'}';
}
}
定义返回码Code类,
//状态码
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
}
修改Controller类的返回值
package com.jkj.controller;
import com.jkj.domain.Book;
import com.jkj.service.BookService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
/* @Autowired
private BookService bookService;
@PostMapping
public Boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@PutMapping
public Boolean update(@RequestBody Book book) {
return bookService.update(book);
}
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Insert id) {
return bookService.delete(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}
@GetMapping
public List getAll() {
return bookService.getAll();
}*/
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
Boolean flag = bookService.save(book);
return new Result(flag?Code.SAVE_OK:Code.SAVE_ERROR,flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
Boolean flag = bookService.update(book);
return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERROR,flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
Boolean flag = bookService.delete(id);
return new Result(flag?Code.DELETE_OK:Code.DELETE_ERROR,flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code=book !=null?Code.SELECT_OK:Code.SAVE_ERROR;
String msg=book !=null ? " " : "数据查询失败";
return new Result(code,book,msg);
}
@GetMapping
public Result getAll() {
List bookList = bookService.getAll();
Integer code=bookList !=null?Code.SELECT_OK:Code.SAVE_ERROR;
String msg=bookList !=null ? " " : "数据查询失败";
return new Result(code,bookList,msg);
}
}
下面是一个查询全部的测试,其他的操作就省略了:

修改BookController类的getById方法,手动添加一个错误信息。
@GetMapping(“/{id}”)
public Result getById(@PathVariable Integer id) {
//手动添加一个错误信息
if(id==1){
int i = 1/0;
}
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String msg = book != null ? “” : “数据查询失败,请重试!”;
return new Result(code,book,msg);
}
测试结果报错:

异常的种类及出现异常的原因:
SpringMVC提供了一套解决方案:
异常处理器:
集中的、统一的处理项目中出现的异常。
@RestControllerAdvice
@ExceptionHandler
package com.jkj.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(Exception.class)
public Result doException(Exception e){
return new Result(666,null);
}
}
业务异常(BusinessException)
系统异常(SystemException)
其他异常(Exception)
异常解决方案的具体实现
BusinessException
package com.jkj.excption;
//自定义异常处理器,用于封装异常信息,对异常进行分类
public class BusinessException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
SystemException
package com.jkj.excption;
//自定义异常处理器,用于封装异常信息,对异常进行分类
public class SystemException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SystemException(Integer code, String message) {
super(message);
this.code = code;
}
public SystemException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
??在BookServiceImpl的getById方法抛异常模拟异常系统和业务异常
public Book getById(Integer id) {
//模拟业务异常,包装成自定义异常
if(id == 1){
throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
}
//模拟系统异常,将可能出现的异常进行包装,转换成自定义异常
try{
int i = 1/0;
}catch (Exception e){
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
}
return bookDao.getById(id);
}
??新增Code类需要的属性
package com.jkj.controller;
public class Code {
public static final Integer SAVE_OK =20011;
public static final Integer UPDATE_OK =20011;
public static final Integer DELETE_OK =20011;
public static final Integer SELECT_OK =20011;
public static final Integer SAVE_ERROR =20010;
public static final Integer UPDATE_ERROR =20010;
public static final Integer DELETE_ERROR =20010;
public static final Integer SELECT_ERROR =20010;
public static final Integer SYSTEM_ERR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
public static final Integer SYSTEM_UNKNOW_ERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
??处理器类中处理自定义异常
package com.jkj.controller;
import com.jkj.excption.BusinessException;
import com.jkj.excption.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ProjectExceptionAdvice {
//@ExceptionHandler用于设置当前处理器类对应的异常类型
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex){
return new Result(ex.getCode(),null,ex.getMessage());
}
//除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
}
}
运行测试:

静态资源这里就不过多描述,篇末会把整个项目传入GitHub中,需要的自取。

添加静态资源后SpringMVC会拦截,需要在SpringConfig的配置类中将静态资源进行放行
在config包下创建
package com.jkj.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“/pages/“).addResourceLocations(”/pages/“);
registry.addResourceHandler(”/css/”).addResourceLocations(“/css/”);
registry.addResourceHandler(“/js/“).addResourceLocations(”/js/“);
registry.addResourceHandler(”/plugins/”).addResourceLocations(“/plugins/”);
}
}
在SpringMvcConfig中扫描SpringMvcSupport
package com.jkj.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan({“com.jkj.service”})
@PropertySource(“classpath:jdbc.properties”)
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
1.created()方法中调用了this.getAll()方法
// 钩子函数,VUE对象初始化完成后自动执行
created() {
this.getAll();
},
2.在getAll()方法中使用axios发送异步请求从后台获取数据
//列表
getAll() {
//发送ajax请求
axios.get("/books").then((res)=>{
this.dataList=res.data.data;
});
},
运行测试:

再此操作之前,需要修改一下前端页面
1.Dao层的增删改方法返回值从void改成int
package com.jkj.dao;
import com.jkj.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface BookDao {
@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
public int save(Book book);
@Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id=#{id}")
public int update(Book book);
@Delete("delete from tbl_book where id=#{id}")
public int delete(Integer id);
@Select("select * from tbl_book where id=#{id}")
public Book getById(Integer id);
@Select("select * from tbl_book")
public List getAll();
}
2.BookServiceImpl中增删改方法根据DAO的返回值来决定返回true/false
package com.jkj.service.impl;
import com.jkj.controller.Code;
import com.jkj.dao.BookDao;
import com.jkj.domain.Book;
import com.jkj.excption.BusinessException;
import com.jkj.excption.SystemException;
import com.jkj.service.BookService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public Boolean save(Book book) {
return bookDao.save(book) > 0;
}
public Boolean update(Book book) {
return bookDao.update(book) > 0;
}
@Override
public Boolean delete(Integer id) {
return bookDao.delete(id) > 0;
}
public Book getById(Integer id) {
return bookDao.getById(id);
}
public List getAll() {
return bookDao.getAll();
}
}
3.找到页面上的新建按钮,按钮上绑定了@click="handleCreate()"方法,在method中找到handleCreate方法,将控制表单设为可见
//弹出添加窗口
handleCreate() {
this.dialogFormVisible=true;
},
4.新增面板中找到确定按钮,按钮上绑定了@click="handleAdd()"方法,在method中找到handleAdd方法,发送请求和数据
axios.post("/books",this.formData).then((res)=>{
//如果操作成功,关闭弹层,显示数据
if(res.data.code == 20011){
this.$message.success("添加成功");
this.dialogFormVisible = false;
}else if(res.data.code == 20010){
this.$message.error("添加失败");
}else{
this.$message.error(res.data.msg);
}
}).finally(()=>{
this.getAll();
});
},
测试:
新增数据:

新增成功:

添加成功后会有信息提示:

新增失败,会有提示信息:

4.小Bug: 每次点击新增的时候,表单都会显示上次新增的信息,需要在 resetForm方法中先清空输入框,在 handleCreate方法中调用 resetForm,来达到每次点击新增功能,表单信息为空。
//弹出添加窗口
handleCreate() {
this.dialogFormVisible=true;
this.resetForm();
},
//重置表单
resetForm() {
//清空输入框
this.formData = {};
},
测试:

1.弹出编辑窗口
找到页面中的编辑按钮,该按钮绑定了@click=“handleUpdate(scope.row)”,在method的handleUpdate方法中发送异步请求根据ID查询图书信息,根据后台返回的结果,判断是否查询成功,如果查询成功打开修改面板回显数据,如果失败提示错误信息。
//弹出编辑窗口
handleUpdate(row){
// console.log(row); //row.id 查询条件
//查询数据,根据id查询
axios.get("/books/"+row.id).then((res)=>{
if(res.data.code == 20041){
//展示弹层,加载数据
this.formData = res.data.data;
this.dialogFormVisible4Edit = true;
}else{
this.$message.error(res.data.msg);
}
});
},
测试:

2.修改后找到修改面板的确定按钮,该按钮绑定了@click=“handleEdit()”,在method,handleEdit方法中发送异步请求提交修改数据,根据后台返回的结果,判断是否修改成功。如果成功提示错误信息,关闭修改面板,重新查询数据,如果失败提示错误信息
//编辑
handleEdit() {
axios.put("/books",this.formData).then((res)=>{
if(res.data.code == 20021){
this.$message.success("修改成功");
this.dialogFormVisible4Edit = false;
}else if(res.data.code == 20020){
this.$message.error("修改失败");
}else{
this.$message.error(res.data.msg);
}
}).finally(()=>{
this.getAll();
});
},
测试:
出bug:结果全部都给修改了。

3.查bug
最终发现通过id修改数据的SQL语句写错了
@Update("update tbl_book set type=#{type},name=#{name},description=#{description} ")
public int update(Book book);
细心的小伙伴会发现忘了写修改条件了:
正确代码:
@Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id=#{id}")
public int update(Book book);
测试:图书名称改为:三体III

测试成功:

找到页面的删除按钮,按钮上绑定了@click=“handleDelete(scope.row)”,method的handleDelete方法弹出提示框,发送异步请求并携带需要删除数据的主键ID
// 删除
handleDelete(row) {
//1.弹出提示框
this.$confirm("此操作永久删除当前数据,是否继续?","提示",{
type:'info'
}).then(()=>{
//2.做删除业务
axios.delete("/books/"+row.id).then((res)=>{
if(res.data.code == 20031){
this.$message.success("删除成功");
}else{
this.$message.error("删除失败");
}
}).finally(()=>{
this.getAll();
});
}).catch(()=>{
//3.取消删除
this.$message.info("取消删除操作");
});
}
想要全面的学习IDEA集成GitHub,这个Git专栏(点击直接学习)里有详细教程。

https://github.com/cainiaolianmengdaduizhang/ssm.git

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦