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

spring-boot学习笔记(二)spring-data-jpa的简介以及项目集成

2018-06-29 14:01 645 查看

一、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层即可使用基本的增删改查方法。


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