SpringBoot基础回顾-14

Spring Boot继承了Spring框架的缓存管理功能,通过使用@EnableCaching注解开启基于注解的缓存支持,Spring Boot就可以启动缓存管理的自动化配置。

接下来针对Spring Boot支持的默认缓存管理进行讲解

5.1.1 基础环境搭建

1.准备数据

使用创建的springbootdata的数据库,该数据库有两个表t_article和t_comment

2.创建项目,功能编写

(1)在Dependencies依赖选择项中添加SQL模块中的JPA依赖、MySQL依赖和Web模块中的Web依赖

(2)编写数据库表对应的实体类,并使用JPA相关注解配置映射关系


      import javax.persistence.*;

      @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;

         
// 省略属性getXX()和setXX()方法

         
// 省略toString()方法

      }

(3)编写数据库操作的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);

}

(4)编写service层


@Service

public class CommentService {

    

   
@Autowired

   
private CommentRepository commentRepository;

 

   
public Comment findCommentById(Integer id){

       
Optional<Comment> comment = commentRepository.findById(id);

       
if(comment.isPresent()){

           
Comment comment1 = comment.get();

           
return comment1;

       
}

       
return null;

    }

    

(5)编写Controller层


@RestController

public class CommentController {

 

   
@Autowired

   
private CommentService commentService;

 

   
@RequestMapping(value = "/findCommentById")

   
public Comment findCommentById(Integer id){

       
Comment comment = commentService.findCommentById(id);

 

       
return comment;

 }

 }

(6)编写配置文件


在项目全局配置文件application.properties中编写对应的数据库连接配置


       #
MySQL数据库连接配置

       spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC

       spring.datasource.username=root

       spring.datasource.password=root

       #显示使用JPA进行数据库查询的SQL语句

       spring.jpa.show-sql=true

       

       #开启驼峰命名匹配映射

       mybatis.configuration.map-underscore-to-camel-case=true

       #解决乱码

       spring.http.encoding.force-response=true

(7)测试

图情况,是因为没有在Spring Boot项目中开启缓存管理。在没有缓存管理的情况下,虽然数据表中的数据没有发生变化,但是每执行一次查询操作(本质是执行同样的SQL语句),都会访问一次数据库并执行一次SQL语句

上了拉勾教育的《Java工程师高薪训练营》,做一下笔记。希望拉勾能给我推到想去的公司,目标:字节!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值