Spring Boot快速入门---(三)spring boot的快速连接数据库之spring data jpa以及事务管理
程序员文章站
2024-03-14 10:27:40
...
五、数据库操作
1.引入依赖
2.在配置文件中添加信息
3.Girl类的书写
4.GirlRepository继承JpaRepository
5.GirlController的实现,可通过Postman来模拟请求
package com.lcz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
/**
* @Author:Coding Chaozhang
*/
@RestController
public class GirlController {
@Autowired
private GirlRepository repository;
@Autowired
private GirlService girlService;
/**
* 查询所有女生列表
* @return
*/
@GetMapping(value = "/girls")
public List<Girl> girlList(){
return repository.findAll();
}
/**
* 创建女生信息
* @param cupSize
* @param age
* @return
*/
@PostMapping(value = "/girls")
public Girl girlAdd(@RequestParam("cupSize")String cupSize,
@RequestParam("age")Integer age){
Girl girl=new Girl();
girl.setAge(age);
girl.setCupSize(cupSize);
return repository.save(girl);
}
/**
* 查询一个女生
* @param id
* @return
*/
@GetMapping(value = "/girls/{id}")
public Optional<Girl> girlFindOne(@PathVariable("id")Integer id){
return repository.findById(id);
}
/**
* 更新一个女生信息
* @param id
* @param cupSize
* @param age
* @return
*/
@PutMapping(value = "/girls/{id}")
public Girl girlUpdate(@PathVariable("id")Integer id,
@RequestParam("cupSize")String cupSize,
@RequestParam("age") Integer age){
Girl girl=new Girl();
girl.setId(id);
girl.setCupSize(cupSize);
girl.setAge(age);
return repository.save(girl);
}
/**
* 删除女生
* @param id
*/
@DeleteMapping(value = "/girls/{id}")
public void girlDelete(@PathVariable("id")Integer id){
repository.deleteById(id);
}
@GetMapping(value = "/girls/age/{age}")
public List<Girl> girlListByAge(@PathVariable("age")Integer age) {
return repository.findByAge(age);
}
@PostMapping(value = "/girls/two")
public void girlTwo(){
girlService.insertTwo();
}
}
六、事务管理
@Transactional
package com.lcz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @Author:Coding Chaozhang
*/
@Service
public class GirlService {
@Autowired
private GirlRepository girlRepository;
@Transactional
public void insertTwo(){
Girl girlA=new Girl();
girlA.setCupSize("A");
girlA.setAge(18);
Girl girlB=new Girl();
girlB.setCupSize("A");
girlB.setAge(18);
girlRepository.save(girlA);
girlRepository.save(girlB);
}
}