Table of Contents
1. Introduction of dependencies
2. Database connection configuration
3. Data object (DO)
4. Persistence object
5. Business layer
6. Test
Home Java javaTutorial How to use JPA as a data persistence framework in SpringBoot

How to use JPA as a data persistence framework in SpringBoot

May 17, 2023 pm 06:13 PM
springboot jpa

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>
Copy after login

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
Copy after login

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 &#39;用户名称&#39;")
    private String name;

    @Column(columnDefinition = "varchar(50) comment &#39;邮箱&#39;")
    private String email;
}
Copy after login
  • @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> {
}
Copy after login

@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;
    }
}
Copy after login

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();
    }
}
Copy after login

Access:

http://localhost:8080/save

Return:

{"id":1,"name":"Asurplus","email":"123456@qq.com"}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Which one is better, jpa or mybatis? Which one is better, jpa or mybatis? Jan 15, 2024 pm 01:48 PM

Choosing JPA or MyBatis depends on specific needs and preferences. Both JPA and MyBatis are Java persistence layer frameworks, and both provide the function of mapping Java objects to database tables. If you need a mature framework that supports cross-database operations, or the project has already adopted JPA as a persistence layer solution, continuing to use JPA may be a better choice. If you want higher performance and more flexible SQL writing capabilities, or are looking for a solution that is less dependent on the database, MyBatis is more suitable.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

See all articles