您的位置:首页 > 编程语言 > Java开发

SpringBoot整合SpringData JPA入门到入坟

2019-04-24 21:18 489 查看

在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);


个人网站

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: