JPA is the abbreviation of Java Persistence API. The Chinese name is Java Persistence Layer API. It is a mapping relationship between JDK 5.0 annotations or XML description objects and relational tables, and persists entity objects at runtime into the database.
1. Introduction of dependencies
<!-- spring mvc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mysql 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- jpa持久层 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
2. Database connection configuration
server: port: 8080 spring: datasource: url: jdbc:mysql://127.0.0.1:3306/jpa-demo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=true&characterEncoding=UTF-8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 jpa: hibernate: # 自动创建表 ddl-auto: update
ddl-auto has a total of five optional values
none: Do nothing
create: Each time hibernate is loaded, the last generated table will be deleted, and then a new table will be generated based on your model class, even if it is twice This is performed even if there are no changes. This is an important reason for the loss of database table data.
create-drop: The table is generated based on the model class every time hibernate is loaded, but the table is automatically deleted as soon as sessionFactory is closed.
update: The most commonly used attribute. When hibernate is loaded for the first time, the table structure will be automatically established based on the model class (provided that the database is established first). When hibernate is loaded later, it will be based on the model class. The class automatically updates the table structure. Even if the table structure changes but the rows in the table still exist, the previous rows will not be deleted. It should be noted that when deployed to the server, the table structure will not be established immediately, but will wait until the application is run for the first time.
validate: Each time hibernate is loaded, the created database table structure is verified. It will only be compared with the table in the database, and no new table will be created, but new values will be inserted.
3. Data object (DO)
import lombok.Data; import javax.persistence.*; @Table(name = "sys_user") @Entity @Data public class SysUserDO { /** * 主键-自增 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(columnDefinition = "varchar(12) comment '用户名称'") private String name; @Column(columnDefinition = "varchar(50) comment '邮箱'") private String email; }
@Id, indicating that this attribute is the primary key field
-
@GeneratedValue(strategy = GenerationType.IDENTITY), using the primary key auto-increment method
@Column, specifies the attributes of the database field, you can set the data type, length, comments and other information , you can also just write an annotation, jpa will automatically identify
4. Persistence object
import com.biz.jpa.entity.SysUserDO; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface SysUserRepository extends JpaRepository<SysUserDO, Long> { }
@Repository, indicating that this is the data access layer
5. Business layer
import com.biz.jpa.dao.SysUserRepository; import com.biz.jpa.entity.SysUserDO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SysUserService { @Autowired private SysUserRepository sysUserRepository; public SysUserDO saveUser() { SysUserDO sysUser = new SysUserDO(); sysUser.setName("Asurplus"); sysUser.setEmail("123456@qq.com"); sysUserRepository.save(sysUser); return sysUser; } }
We insert a piece of data into the sys_user table. Since the primary key is automatically incremented, we do not need to set the primary key. After the insertion is successful, the auto-incremented primary key will be automatically written back to the object
6. Test
import com.biz.jpa.entity.SysUserDO; import com.biz.jpa.service.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SysUserController { @Autowired private SysUserService sysUserService; @GetMapping("save") public SysUserDO save() { return sysUserService.saveUser(); } }
Access:
http://localhost:8080/save
Return:
{"id":1,"name":"Asurplus","email":"123456@qq.com"}
The insertion is successful and the auto-incremented primary key is returned. The integration of Jpa is completed here. More usage of Jpa needs to be explored in actual project development.
The above is the detailed content of How to use JPA as a data persistence framework in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools