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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools