本文共 2928 字,大约阅读时间需要 9 分钟。
Springboot + jpa 上面是代码
配置
spring: datasource: url: jdbc:mysql://localhost:3306/demo username: root password: root driver-class-name: com.mysql.jdbc.Driver jpa: # jpa 配置 database: mysql show-sql: true hibernate: ddl-auto: update devtools: # 热部署配置 restart: enabled: true
实体类
mport javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;/** * * @author rainyday * @createTime 2018/7/2. */@Entitypublic class Cat { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String catName; private int catAge; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } public int getCatAge() { return catAge; } public void setCatAge(int catAge) { this.catAge = catAge; }}
继承
CrudRepository
可以直接调用 jpa的方法
import org.springframework.data.repository.CrudRepository;import springboot.bean.Cat;public interface CatRepository extends CrudRepository{}
Service层
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import springboot.bean.Cat;import springboot.repository.CatRepository;/** * @author rainyday * @createTime 2018/7/2. */@Servicepublic class CatService { @Autowired private CatRepository catRepository; @Transactional public void save(Cat cat) { catRepository.save(cat); } @Transactional public void delete(int id) { catRepository.deleteById(id); } @Cacheable("getAll") public IterablegetAll() { System.out.println("no use cache"); return catRepository.findAll(); }}
控制层
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.*;import springboot.bean.Cat;import springboot.service.CatService;/** * @author rainyday * @createTime 2018/7/2. */@RestController@RequestMapping("/cat")public class CatController { @Autowired private CatService catService; @PostMapping("/save") public void save(@RequestParam(required = false) Cat cat) { if (StringUtils.isEmpty(cat)) { cat = new Cat(); cat.setCatName("jack"); } cat.setCatAge(3); catService.save(cat); } @RequestMapping("delete") public String delete() { catService.delete(1); return "delete ok!"; } public IterablegetAll() { return catService.getAll(); }}