SpringBoot实操(4)

今日目标

  • 事务处理

概念介绍

什么是事务处理?

事务处理就是要保持数据库的安全性。

事务要么完全地执行,要么完全地不执行。

事务处理可以确保除非事务性单元内的所有操作都成功完成。

IDEA操作

事务处理

第一步

事务处理是保持数据库的安全性的一种处理方法,所以SpringBoot中,要部署好了Mybatis和MybatisGenerator。

SpringBoot中要完成xml,properties,dao,entity,mapper/*.xml,mybatisGeneratorConfig.xml的配置,可以参考上面的文章。

底层的数据库和表也要建好。

image.png

第二步

事务一般不放在controller文件夹中,新建src/main/java/com/example/demo/service/TransactionTestService.java,代码如下:

package com.example.demo.service;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service
public class TransactionTestService {
    @Resource
    UserDao userDao;
    public Boolean test1(){
        User user=new User();
        user.setPassword("test1-password");
        user.setName("test1");
        userDao.insertUser(user);
        System.out.println(1/0);
        return true;
    }
    @Transactional
    public Boolean test2(){
        User user=new User();
        user.setPassword("test2-password");
        user.setName("test2");
        userDao.insertUser(user);
        System.out.println(1/0);
        return true;
    }
}

可以看到test1和test2函数的区别就在于一个有@Transactional,一个没有。

这也就决定了一个可以test1的插入可以执行,是不安全的。

test2是事务性的,数据库表中不会出现name=test2的数据。

第三步

编写TransactionTestController.java,代码如下:

package com.example.demo.controller;

import com.example.demo.service.TransactionTestService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
public class TransactionTestController {
    @Resource
    private TransactionTestService transactionTestService;
    @GetMapping("/transactionTest")
    @ResponseBody
    public String transactionTest(){
        transactionTestService.test1();
        transactionTestService.test2();
        return "done";
    }
}

通过访问/transactionTest执行test1方法和test2方法。

第四步

访问localhost:8080/transactionTest会发现报错,不过只观察数据库中的变化就可以了。

image.png

可以发现:test1中即使发生了错误,数据还是被插入了。而test2中发生了错误,事务回滚,插入没有执行。

Ajax

Ajax 技术使得网站与用户间有了更友好的交互效果,比较常见的借助 Ajax 技术实现的功能有列表上拉加载分页数据、省市区三级联动、进度条更新等等,这些都是借助 Ajax 技术在当前页面即可完成的功能,即使有数据交互也不会跳转页面,整体交互效果有了很大的提升。

RESTful

目前比较流行的一套接口规范就是 RESTful api,REST(Representational State Transfer),中文翻译叫"表述性状态转移"

重温Bootstrap和JQuery

敬请期待

AdminLTE

可能要做一些SpringBoot实操教程的改变了,像我这样的初学者还是应该跟着教程然后一步一步来

image.png

如果图片无法加载,可以访问我的原博客

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务