使用Spring Assistant创建1.5.18jar工程。
application.yml文件内容
添加YAML Ansible support插件,文件后缀名yaml。
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/demo username: root password: 123456 jpa: hibernate: ddl-auto: update show-sql: true
创建Entity类Girl,会自动生成(更新)数据库中的表,名称就是girl
全部
package com.example;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class Girl { @Id @GeneratedValue private Integer id; private String cupSize; private Integer age; public Girl() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCupSize() { return cupSize; } public void setCupSize(String cupSize) { this.cupSize = cupSize; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }}
创建接口GirlRepository
public interface GirlRepository extends JpaRepository{ //lookup by age public List findByAge(Integer age);}
Controller中使用GirlRepository对象来增删改查
增
删
改
查
package com.example;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.List;@RestControllerpublic class GirlController { @Autowired private GirlRepository girlRepository; @Autowired private GirlService girlService; //查询所有girl @GetMapping("/girls") public ListgirlList() { return girlRepository.findAll(); } //增加一个girl @GetMapping("/add") public Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl=new Girl(); girl.setAge(age); girl.setCupSize(cupSize); return girlRepository.save(girl); } //根据一个id查询girl @GetMapping("/girls/{id}") public Girl findTheGirl(@PathVariable("id") Integer id) { return girlRepository.findOne(id); } //根据id更新girl @GetMapping("/girls/update/{id}") public Girl updateTheGirl(@PathVariable("id") Integer id,@RequestParam("age") Integer age, @RequestParam("cupSize") String cupSize) { Girl girl=new Girl(); girl.setId(id); girl.setAge(age); girl.setCupSize(cupSize); return girlRepository.save(girl); } //根据id删除girl @GetMapping("/girls/remove/{id}") public void deleteGirl(@PathVariable("id") Integer id) { girlRepository.delete(id); } @GetMapping("/girls/age") public List findByA(@RequestParam("age") Integer age) { return girlRepository.findByAge(age); } @GetMapping("girls/testTrans") public void testTrans() { girlService.insertTwo(); }}
使用事务
业务类中的方法加上@Transactional即可
@Servicepublic class GirlService { @Autowired private GirlRepository girlRepository; @Transactional public void insertTwo() { Girl girlA=new Girl(); girlA.setCupSize("F"); girlA.setAge(17); girlRepository.save(girlA); int a=3/0;//发生异常,前面的数据库操作无效 Girl girlB=new Girl(); girlB.setAge(22); girlB.setCupSize("B"); girlRepository.save(girlB); }}