springBoot事务管理

springBoot事务管理

demo:

GirlController:

@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    /**
     * 插入(事物管理)
     */
    @PostMapping(value = "/girls/two")
    public void girlTwo(){
        girlService.insertTwo();
    }

}

GirlService:

@Service
public class GirlService {

    @Autowired
    private GirlRepository girlRepository;

    /**
     * 事务管理
     * 该方法中的两个操作要么都成功,要么都失败
     * 一般只有一个操作也要加事务管理,只要查询不需要加
     */
    @Transactional
    public void insertTwo(){
        Girl girlA = new Girl();
        girlA.setCupSize("A");
        girlA.setAge(18);
        girlRepository.save(girlA);

        Girl girlB = new Girl();
        girlA.setCupSize("B");
        girlA.setAge(19);
        girlRepository.save(girlB);
    }


}

GirlRepository:

public interface GirlRepository extends JpaRepository<Girl,Integer> {
    /**JpaRepository<>
     * 第一个参数:类名
     * 第二个参数:id的类型
     */

    //通过年龄来查询
    public List<Girl> findByAge(Integer age);


}

Girl:

@Entity //该注解表示该类在数据库中有对应的表 不用创建该表
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;

    private String cupSize;

    private Integer age;

    public Girl() {
    }

applicaion.yml:

spring:
  profiles:
    active: prod
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/dbgirl
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 之前搭建的Spring boot Mybatis 整合(注解版)中我们简单的使用了springboot的事务管理,...
    Winter_Chen阅读 966评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,410评论 19 139
  • 概要 springboot简介 搭建普通的maven项目(本例已maven为例) springboot hello...
    小乐xing阅读 857评论 1 3
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,249评论 6 342
  • 写在前面 ======通过阅读官方文档以及编写一些demo,个人认为spring boot的核心思想是约定大于配置...
    ImushroomT阅读 6,585评论 1 8

友情链接更多精彩内容