Skip to main content

事务管理

如何使用事务

@Transactional 注解就行了

举个例子

创建Service

注意加 @Service 注解

package cn.asdasd.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class GirlService {

@Autowired
private GirlRepository girlRepository;

@Transactional
public void insertTwo(){
Girl girlA = new Girl();
girlA.setId(1);
girlA.setCupSize("A");
girlA.setAge(20);
girlRepository.save(girlA);

Girl girlB = new Girl();
girlB.setId(2);
girlB.setCupSize("BBBBBB");
girlB.setAge(22);
girlRepository.save(girlB);

}
}

Controller 里调用

注意 不要忘记 @Autowired

@Autowired
private GirlService girlService;

package cn.asdasd.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GirlController {

@Autowired
private GirlRepository girlRepository;

@Autowired
private GirlService girlService;

@PostMapping(value = "/girls/two")
public void girlTwo() {
girlService.insertTwo();
}

}