基础环境搭建
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 extendsJpaRepository<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层
@Servicepublic 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层
@RestControllerpublic 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工程师高薪训练营》,看到刚学到的点就回答了。希望拉勾能给我推到想去的公司,目标:字节!!