在pom.xml中加入如下依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
application.properties
##端口號
server.port=8888
##數據庫配置
##數據庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##數據庫用戶名
spring.datasource.username=root
##數據庫密碼
spring.datasource.password=1234
##數據庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
##validate 加載hibernate時,驗證創建數據庫表結構
##create 每次加載hibernate,重新創建數據庫表結構,這就是導致數據庫表數據丟失的原因。
##create-drop 加載hibernate時創建,退出是刪除表結構
##update 加載hibernate自動更新數據庫結構
##validate 啟動時驗證表的結構,不會創建表
##none 啟動時不做任何操作
spring.jpa.hibernate.ddl-auto=update
##控制台打印sql
spring.jpa.show-sql=true
House.java實體類加上@Entity注解
@Entity
public class House {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(length = 10)
private String houseName;
private String houseSize;
//省略set.get方法及構造器
}
HouseRepository.java接口繼承JpaRepository
public interface HouseRepository extends JpaRepository<House, Integer> {
}
HouseController.java
@RestController
public class HouseController {
@Autowired
private HouseRepository houseRepository;
// @CachePut注解,這個注解直接將返回值放入緩存中,通常用於保存和修改方法中
@GetMapping("/saveHouse")
@CachePut(value = "house", key = "#id")
public House saveHouse(Integer id, String houseName, String houseSize) {
House house = new House(id, houseName, houseSize);
houseRepository.save(house);
return house;
}
//@Cacheable注解,這個注解在執行前先查看緩存中是不是已經存在了,如果存在,直接返回。如果不存在,將方法的返回值放入緩存。
@GetMapping("/queryHouse")
@Cacheable(value = "house", key = "#id")
public House queryHouse(Integer id) {
House house = houseRepository.findOne(id);
return house;
}
//@CacheEvict注解,這個注解在執行方法執行成功后會從緩存中移除
@GetMapping("/deleteHouse")
@CacheEvict(value = "house", key = "#id")
public String deleteHouse(Integer id) {
houseRepository.delete(id);
return "刪除成功";
}
//@CacheEvict注解,不同的是使用了allEntries熟悉,默認為false,true的時候移除所有緩存。
@GetMapping("/deleteCacheAll")
@CacheEvict(value = "house", allEntries = true)
public String deleteCacheAll() {
return "刪除所有緩存";
}
}
最后務必記得在啟動類加上注解@EnableCaching開啟緩存,否則無效
注意以下點
出現這種問題的原因是,springboot 版本問題,將 2。1 版本換成 1。5。4 版本。
或者是將代碼改寫一下
return girlRepository.findOne(id);
return girlRepository.findById(id).orElse(null);