Java Persistence API(JPA)是一种Java规范,用于访问,持久化和管理Java对象/类与关系数据库之间的数据。JPA被定义为EJB 3.0规范的一部分,以替代EJB 2 CMP Entity Beans规范。现在,JPA被认为是Java行业中对象到关系映射(ORM)的标准行业方法。
持久化,在这里包括三个层面的意思:
内
目前实现JPA规范的ORM框架有 Hibernate(推荐使用)、OpenJPA、TopLink
pom.xml
文件
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.4.3version>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>accessing-data-mysqlartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>accessing-data-mysqlname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
application.properties
文件Spring Boot为您提供所有默认设置。例如,默认数据库为H2
。因此,当您要使用任何其他数据库时,必须在application.properties
文件中定义连接属性。
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
在这里,spring.jpa.hibernate.ddl-auto
可以是none
,update
,create
,或create-drop
。有关详细信息,请参见Hibernate文档。
none
:的默认设置MySQL
。数据库结构未做任何更改。update
:Hibernate根据给定的实体结构更改数据库。create
:每次都创建数据库,但不会在关闭时将其删除。create-drop
:创建数据库,并在SessionFactory
关闭时将其删除。@Entity
模型package com.kang.jpa.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer id;
private String name;
private String email;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Spring Data JPA专注于使用JPA将数据存储在关系数据库中。它最引人注目的功能是能够在运行时,从repository接口自动创建repository实现。
package com.kang.jpa.repository;
import com.kang.jpa.entity.User;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Integer> {
}
package com.kang.jpa.controller;
import com.kang.jpa.entity.User;
import com.kang.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path="/user") // This means URL's start with /demo (after Application path)
public class UserController {
@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody
String addNewUser (@RequestParam String name
, @RequestParam String email) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request
User n = new User();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "Saved";
}
@GetMapping(path="/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}
package com.kang.jpa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootJpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootJpaApplication.class, args);
}
}
@SpringBootApplication
包含下面所有的注释,它添加了以下所有内容:
@Configuration
:将类标记为应用程序上下文的Bean定义的来源。@EnableAutoConfiguration
:告诉Spring Boot根据类路径设置,其他bean和各种属性设置开始添加bean。例如,如果spring-webmvc
在类路径上,则此注释将应用程序标记为Web应用程序并激活关键行为,例如设置DispatcherServlet
。@ComponentScan
:告诉Spring在包中寻找其他组件,配置和服务com/example
,让它找到控制器。运行应用程序时,将显示日志记录输出。
GET localhost:8080/demo/all
:获取所有数据。
POST localhost:8080/demo/add
:将一个用户添加到数据中。
curl -X POST -d '[email protected]' http://127.0.0.1:8080/user/add
# 添加用户
curl -X GET http://localhost:8080/user/all
# 查询所有用户
https://en.wikibooks.org/wiki/Java_Persistence/What_is_JPA%3F
https://spring.io/guides/gs/accessing-data-jpa/
https://spring.io/guides/gs/accessing-data-mysql/