SpringBoot整合Jpa实现增删改查功能(提供Gitee源码)

前言:在日常开发中,总是撰写一些简单的SQL会非常耗时间,Jpa可以完美的帮我们提高开发的效率,对于常规的SQL不需要我们自己撰写,相对于MyBatis有着更简单易用的功能,但是MyBatis自由度相对于Jpa会更高一些,所以Jpa比较适用于一些中小型的项目开发,提高开发人员的开发效率,下面我就完整的介绍一下SpringBoot是如何整合Jpa来实现完整的增删改查功能的。

目录

一、导入pom依赖

二、yml配置文件

三、表结构SQL

四、User实体类

五、Dao持久层

六、使用示例

6.1、查询名为张三的用户

6.2、分页查询数据

6.3、自定义SQL查询

6.4、新增一条用户数据

6.5、修改一条用户数据

6.6、删除一条用户数据

七、Gitee源码

八、总结


一、导入pom依赖

完整代码:

XML 复制代码
<dependencies>

        <!-- JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- MySQL驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <!-- lombok依赖包 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
    </dependencies>

二、yml配置文件

完整代码:

XML 复制代码
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: 用户名
    password: 密码
  # JPA配置
  jpa:
    # 在建表的时候,将默认的存储引擎切换为InnoDB
    database-platform: org.hibernate.dialect.MySQLDialect
    # 数据源
    database: mysql
    # 控制台显示sql
    show-sql: true
    hibernate:
      # 更新或创建表结构
      ddl-auto: update

三、表结构SQL

完整代码:

sql 复制代码
-- jpa.`user` definition

CREATE TABLE `user` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `age` bigint NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

四、User实体类

常见用于实体类注解如下:

1、@Entity:用于将一个类标记为JPA实体类,表示这个类将映射到数据库中的一个表。在JPA中,实体类必须使用@Entity注解进行标记,以便JPA能够识别并管理它。

2、@Table:用于指定实体类对应的数据库表的名称和约束。

name:指定表的名称。

schema:指定表所在的数据库模式。

catalog:指定表所在的数据库目录。

uniqueConstraints:指定表的唯一约束。

3、@Column:用于指定实体类属性与数据库表字段的映射关系。

name:指定字段的名称。

nullable:指定字段是否可为空。

unique:指定字段是否唯一。

length:指定字段的长度。

precision:指定字段的精度。

scale:指定字段的小数位数。

4、@Id:用于指定实体类属性作为主键。

5、@GeneratedValue:用于指定主键的生成策略。

strategy:指定主键生成策略,如AUTO、IDENTITY、SEQUENCE等。

6、@Transient:用于指定实体类属性不需要持久化到数据库。

7、@Access:用于指定属性的访问方式,如FIELD、PROPERTY等。

8、@Temporal:用于指定实体类属性与数据库表字段的日期/时间类型映射。

value:指定日期/时间类型,如DATE、TIME、TIMESTAMP等。

9、@Enumerated:用于指定实体类属性与数据库表字段的枚举类型映射。

value:指定枚举类型映射方式,如ORDINAL、STRING等。

10、@Embedded:用于指定实体类属性为嵌入式对象。

11、@Embeddable:用于指定嵌入式对象。

12、@OneToOne:用于指定实体类之间的一对一关系。

13、@JoinColumn:用于指定外键列的名称和约束。

14、@OneToMany:用于指定实体类之间的一对多关系。

15、@JoinColumn:用于指定外键列的名称和约束。

16、@OrderBy:用于指定集合属性的排序方式。

17、@ManyToOne:用于指定实体类之间的多对一关系。

18、@JoinColumn:用于指定外键列的名称和约束。

19、@ManyToMany:用于指定实体类之间的多对多关系。

20、@JoinTable:用于指定中间表的名称和约束。

21、@JoinColumn:用于指定外键列的名称和约束。

完整代码:

java 复制代码
package com.example.jpa.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user")
public class User {

    @Id
    @Column(name = "id",nullable = false)
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username",nullable = false,length = 100)
    private String username;

    @Column(name = "password",nullable = false,length = 100)
    private String password;

    @Column(name = "sex",nullable = false,length = 1)
    private String sex;

    @Column(name = "address",length = 100)
    private String address;

    @Column(name = "age",nullable = false)
    private int age;
}

五、Dao持久层

完整代码:

java 复制代码
package com.example.jpa.dao;

import com.example.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserRepository extends JpaRepository<User,Long> {

    /**
     * 根据用户名去查询用户信息
     * @return
     */
    public User findUserByUsername(@Param("username") String username);
    
    /**
     * 自定义SQL查询
     * @return
     */
    @Query(value="select * from user where address like %:address%",nativeQuery=true)
    List<User> findUserByAddressSQL(@Param("address") String address);


}

六、使用示例

以下列举一些基本的增删改查功能。

6.1、查询名为张三的用户

完整代码:

java 复制代码
package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        User user = userRepository.findUserByUsername("张三");
        System.out.println(user);
    }

}

6.2、分页查询数据

完整代码:

java 复制代码
package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        Pageable pageable = PageRequest.of(1, 10);
        Page<User> userPage = userRepository.findAll(pageable);
        List<User> userList = userPage.getContent();
    }

}

6.3、自定义SQL查询

完整代码:

java 复制代码
package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        List<User> userList = userRepository.findUserByAddressSQL("江苏");
    }

}

6.4、新增一条用户数据

完整代码:

java 复制代码
package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.*;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        User user = new User();
        user.setUsername("李四");
        user.setPassword(UUID.randomUUID().toString());
        user.setAddress("江苏南通");
        user.setAge(18);
        user.setSex("男");
        userRepository.save(user);
    }

}

6.5、修改一条用户数据

完整代码:

java 复制代码
package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.UUID;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        User findUserByUsername = userRepository.findUserByUsername("张三");
        findUserByUsername.setPassword(UUID.randomUUID().toString());
        userRepository.save(findUserByUsername);
    }

}

6.6、删除一条用户数据

完整代码:

java 复制代码
package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        userRepository.deleteById(18L);
    }

}

七、Gitee源码

码云地址:SpringBoot整合Jpa实现增删改查功能

八、总结

以上就是我对SpringBoot整合Jpa实现增删改查基本功能分享,如有问题,欢迎评论区讨论!

相关推荐
ladymorgana3 分钟前
【docker】修改 MySQL 密码后 Navicat 仍能用原密码连接
mysql·adb·docker
hello早上好3 分钟前
JDK 代理原理
java·spring boot·spring
PanZonghui6 分钟前
Centos项目部署之安装数据库MySQL8
linux·后端·mysql
PanZonghui8 分钟前
Centos项目部署之运行SpringBoot打包后的jar文件
linux·spring boot
PanZonghui8 分钟前
Centos项目部署之Java安装与配置
java·linux
Victor3569 分钟前
MySQL(119)如何加密存储敏感数据?
后端
用户39661446871920 分钟前
TypeScript 系统入门到项目实战-慕课网
后端
GreatSQL社区22 分钟前
用systemd管理GreatSQL服务详解
数据库·mysql·greatsql
掘根22 分钟前
【MySQL进阶】错误日志,二进制日志,mysql系统库
数据库·mysql