基础环境搭建
数据库
创建项目
创建一个springboot项目,并导入JPA、MySQL和web项目依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
编写实体类
@Data
@Entity(name = "t_comment")// 设置ORM实体类,并指定映射的表名
public class Comment {
@Id // 表明映射对应的主键id
@GeneratedValue(strategy = GenerationType.IDENTITY)//设置主键自增策略
private Integer id;
private String content;
private String author;
@Column(name = "a_id")// 指定映射的表字段名
private Integer aId;
}
编写Repository接口文件
public interface CommentRepository extends JpaRepository<Comment,Integer> {
// 根据评论id修改评论作者评论作者author
@Transactional
@Modifying
@Query("UPDATE t_comment c SET c.author= ?1 WHERE c.id = ?2")
public int updateComment(String author,Integer id);//修改评论的方法
}
编写Service文件
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
// 根据评论id查询评论信息
public Comment findById(int comment_id) {
Optional<Comment> optional = commentRepository.findById(comment_id);
if (optional.isPresent()) {
return optional.get();
}
return null;
}
// 更新评论信息
public Comment updateComment(Comment comment) {
commentRepository.updateComment(comment.getAuthor(), comment.getAId());
return comment;
}
// 删除评论信息
public void deleteComment(int comment_id) {
commentRepository.deleteById(comment_id);
}
}
编写Controller类
@RestController
public class CommentController {
@Autowired
private CommentService commentService;
@GetMapping("/get/{id}")
public Comment findById(@PathVariable("id") int comment_id) {
Comment comment = commentService.findById(comment_id);
return comment;
}
@GetMapping("/update/{id}/{author}")
public Comment updateComment(@PathVariable("id") int comment_id,
@PathVariable("author") String author) {
Comment comment = commentService.findById(comment_id);
comment.setAuthor(author);
Comment updateComment = commentService.updateComment(comment);
return updateComment;
}
@GetMapping("/delete/{id}")
public void deleteComment(@PathVariable("id") int comment_id) {
commentService.deleteComment(comment_id);
}
}
编写配置文件
# MySQL数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&useSSL=false
spring.datasource.username=
spring.datasource.password=
# 显示使用JPA进行数据库查询的SQL语句
spring.jpa.show-sql=true
运行测试
启动项目,访问http://localhost:8080/get/1
此时如果刷新浏览器, 通过IDEA的输出可以发现,会再次执行查询操作,当用户量增加时,数据规模不断变大,此时会影响用户体验。因此使用缓存是一个不错的选择。
SpringBoot默认缓存
Spring Boot支持的缓存组件有:
- Generic
- JCache (JSR-107) (EhCache 3、Hazelcast、Infinispan等)
- EhCache 2.x
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple(默认)
这里介绍默认缓存
在启动类加入@EnableCaching注解
@EnableCaching//开启Spring Boot基于注解的缓存管理支持
@SpringBootApplication
public class Chapter06Application {
public static void main(String[] args) {
SpringApplication.run(Chapter06Application.class, args);
}
}
在Service类的方法上添加注解(注解类型见注释)
@Service
@CacheConfig(cacheNames = "comment")
/*
主要用于统筹管理类中所有使用@Cacheable、@CachePut和@CacheEvict注解标注方法中的公共属性,
这些公共属性包括有cacheNames、keyGenerator、cacheManager和cacheResolver
比如我在此处使用cacheNames = "comment",则以下的@Cacheable、@CachePut和@CacheEvict中可不必添加属性cacheNames = "comment"
但如果有,就会遵循就近原则,以方法注解属性为准
*/
public class CommentService {
@Autowired
private CommentRepository commentRepository;
// 根据评论id查询评论信息
@Cacheable(cacheNames = "comment", unless = "#result==null")
/*
先进行缓存查询,如果为空则进行方法查询,并将结果进行缓存;如果缓存中有数据,不进行方法查询,而是直接使用缓存数据。
value/cacheNames:指定缓存空间的名称,必配属性。这两个属性二选一使用
key:指定缓存数据的key,默认使用方法参数值,可以使用SpEL表达式
keyGenerator:指定缓存数据的ktey的生成器,与key属性二选一使用
cacheManager:指定缓存管理器
cacheResolxer.;指定缓存解析器,与cacheManager属性二选一使用
condition:指定在符合某条件下,进行数据缓存
unless:指定在符合某条件下,不进行数据缓存
sync:指定是否使用异步缓存。默认false
*/
public Comment findById(int comment_id) {
Optional<Comment> optional = commentRepository.findById(comment_id);
if (optional.isPresent()) {
return optional.get();
}
return null;
}
// 更新评论信息
@CachePut(cacheNames = "comment", key = "#result.id")
/*
该注解的作用是更新缓存数据。默认执行顺序是,先进行方法调用,然后将方法结果更新到缓存中
*/
public Comment updateComment(Comment comment) {
commentRepository.updateComment(comment.getAuthor(), comment.getAId());
return comment;
}
// 删除评论信息
@CacheEvict(cacheNames = "comment")
/*
该注解的作用是删除缓存数据。默认执行顺序是,先进行方法调用,然后将缓存进行清除。
*/
public void deleteComment(int comment_id) {
commentRepository.deleteById(comment_id);
}
/*
@Caching注解用于针对复杂规则的数据缓存管理,可以作用于类或方法,在@Caching注解内部包含有Cacheable、put和evict三个属性,分别对应于@Cacheable、@CachePut和@CacheEvict三个注解。
*/
@Caching(cacheable = {@Cacheable(cacheNames = "comment", key = "#id")},
put = {@CachePut(cacheNames = "comment", key = "#result.author")})
public Comment getComment(int comment_id) {
return commentRepository.findById(comment_id).get();
}
}
重复进行同样的查询操作,数据库只执行了一次SQL查询语句,说明项目开启的默认缓存支持已经生效。