作者:CJT--陳嘉婷 | 来源:互联网 | 2023-06-22 21:06
五、数据库操作1.引入依赖2.在配置文件中添加信息3.Girl类的书写4.GirlRepository继承JpaRepository5.GirlController的实现ÿ
五、数据库操作
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 {@Autowiredprivate GirlRepository repository;@Autowiredprivate GirlService girlService;/*** 查询所有女生列表* @return*/@GetMapping(value = "/girls")public List 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 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 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 {@Autowiredprivate GirlRepository girlRepository;@Transactionalpublic 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);}
}