1. 程式人生 > >Springboot jpa 本人親測 附有程式碼

Springboot jpa 本人親測 附有程式碼

程式碼

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.
 */
@Entity
public 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<Cat, Integer>{
}

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.
 */
@Service
public 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 Iterable<Cat> getAll() {
        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 Iterable<Cat> getAll() {
        return catService.getAll();
}

}