1.引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- SpringDataJPA依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.配置文件application.properties
# 数据源DataSource
spring.datasource.url=jdbc:mysql://8.129.176.154:3307/addressbook?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#SpringDataJPA的配置
#创建数据库的方式类型 update:当实体类有属性变动时,表就会跟着更新
spring.jpa.hibernate.ddl-auto=update
#显示对应操作的sql语句
spring.jpa.show-sql=true
3.创建实体类
@Entity //指明此类是与数据库表对应的实体类
@Table(name = "t_user") //指名 此类对应的表名
public class User {
@Id //指明此属性 是主键
@GeneratedValue(strategy = GenerationType.IDENTITY) //主键自增,也即:数据表的主键自增
private Integer id;
@Column(name = "name")
private String name;
private String number;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
注:若实体类中属性名与数据库中字段名不同,需要用 @Column(name="t_name")指明映射关系
4.SpringBoot JPA提供的核心接口
1、Repository接口
2、CrudRepository接口
3、PagingAndSortingRepository接口
4、JpaRepository接口
5、JPASpecificationExecutor接口
5.主要学习JpaRepository接口,创建持久化接口,简化操作持久层的代码,只需要编写接口就可以
注:创建一个接口,继承接口 JpaRepository<类名,类的主键属性的类型>
public interface UserRepository extends JpaRepository<User,Integer> {
}
6.发送请求测试
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/hello")
public Object hello(){
return "hello";
}
@RequestMapping("/save")
public void save(){
User user = new User();
user.setName("xiaomeimei");
user.setNumber("15999999999");
userRepository.save(user);
}
@RequestMapping("/find")
public Object find(){
return userRepository.findAll();
}
}