spring-boot学习笔记(二)spring-data-jpa的简介以及项目集成
【摘要】 spring-boot学习笔记(二)spring-data-jpa的简介以及项目集成
一、spring-data-jpa简介及其用法
spring-data-jpa 常用接口
1.CrudRepository接口继承了repository接口,包含了基本的增删改查方法
2.PagingAndSortingRepository接口继承了CrudRepository接口,增加了分页以及排序的方法
二、spring-boot项目集成jpa
1.在build.gradle文件中添加spring-data-jpa 和 h2 数据源的依赖 依赖
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
runtime('com.h2database:h2:1.4.196')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('mysql:mysql-connector-java:6.0.5')
}
2.在application.properties文件中添加连接数据库的配置
#Thymeleaf 编码 spring.thymeleaf.encoding=UTF-8 #热部署静态文件 spring.thymeleaf.cache=false #使用html5标准 spring.thymeleaf.mode=HTML5 #启用h2控制台,可以查看数据,localhost:8080/h2-console 可以访问到 h2控制台
spring.h2.console.enabled=true #datasource spring.datasource.url=jdbc:mysql://localhost/blog?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=1234 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #jpa spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
3.实体类中添加@Entity注解,String Long id;添加 @Id注解以及生成规则
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY) //自增策略
private Long id;
private String name;
private String email;
public User() { //spring-data-jpa 规定要有 实体类要有无参构造方法(即重写了有参数构造一定要显示定义该无参构造方法)
super();
}
4.编写接口UserRepository继承 CrudRepository<User, Long>,将UserRepository注入到controller层即可使用基本的增删改查方法。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)