美文网首页
持久层框架JPA之枚举值处理

持久层框架JPA之枚举值处理

作者: 程序员小白成长记 | 来源:发表于2023-03-03 18:51 被阅读0次

    DEMO实现枚举值的增查

    1. entity

    其中status字段为枚举类型,存入数据库的是对应的枚举值的值
    StudentStatusEnum status缺点是枚举值可以为String和int类型,但是int类型会按照0开始,如果包含了枚举值为-1,或者乱序的情况无法处理,参考解决JPA的枚举局限性

    @Data
    @Entity
    @NoArgsConstructor
    @AllArgsConstructor
    @Table(name = "student", indexes =
            {
                    @Index(name = "idx_stu_no", columnList = "stu_no")
            }
    )
    public class Student {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id", length = 20)
        @Comment("Primary Key, auto increment")
        private Long id;
    
        @Column(name = "stu_no", nullable = false, length = 20)
        @Comment("student number")
        private Long stuNo;
    
        @Column(name = "stu_name", nullable = false, length = 50)
        @Comment("student name")
        private String stuName;
    
        @Column(name = "age", nullable = false)
        @Comment("age")
        private Integer age;
    
        @Column(name = "last_execute_timestamp", nullable = false)
        @Comment("register date")
        private LocalDateTime registerDate;
    
        @Column(name = "status", nullable = false)
        @Comment("0: inactive, 1: active")
        private StudentStatusEnum status;
    }
    
    
    public enum StudentStatusEnum {
        INACTIVE(0),
        UNACTIVE(1);
    
        private final int code;
    
        StudentStatusEnum(final int code) {
            this.code = code;
        }
    
        public int getCode() {
            return this.code;
        }
    }
    

    repository

    注意stu.status = com.user.common.enums.StudentStatusEnum.INACTIVE写法,之所以能这么写因为Entity中status字段为枚举类型。

    @Repository
    public interface StudentRepo extends JpaRepository<Student, Long>, PagingAndSortingRepository<Student, Long>, JpaSpecificationExecutor<Student> {
    
        @Query(value =
                "SELECT stu " +
                "FROM  Student stu " +
                "WHERE stu.status = com.user.common.enums.StudentStatusEnum.INACTIVE " +
                "   or (stu.status = com.user.common.enums.StudentStatusEnum.UNACTIVE)"
                )
        List<Student> getStudent1();
    }
    

    Test

    // @Ignore
    @DataJpaTest
    @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
    class StudentRepoTest extends Specification {
        @Autowired
        StudentRepo studentRepo
    
    
        @Commit
        def "save student"() {
            given:
            Student student = new Student()
            student.stuNo = 111L
            student.stuName = "neo"
            student.age = 18
            student.registerDate = LocalDateTime.now()
            student.status = StudentStatusEnum.INACTIVE
    
    
    
            when:
            def res = studentRepo.save(student)
    
            then:
            res.stuNo == 111L
        }
    
        def "get student"() {
            given:
            void
    
            when:
            def student = studentRepo.getStudent1();
    
            then:
            student.size() == 1
        }
    }
    

    application.yml

    spring:
      jpa: #Jpa configuration. update or automatic table generation, console print sql
        database: mysql
        show-sql: true
        properties:
          hibernate:
            format_sql: true
            # generate_statistics: true
        hibernate:
          ddl-auto: update
          naming:
            implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
            physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    

    数据库表

    因为jpa配置了ddl-auto: update,所以执行单测时会自动创建表

    CREATE TABLE `student` (
      `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'Primary Key, auto increment',
      `age` int NOT NULL COMMENT 'age',
      `last_execute_timestamp` datetime(6) NOT NULL COMMENT 'register date',
      `status` int NOT NULL COMMENT '0: inactive, 1: active',
      `stu_no` bigint NOT NULL COMMENT 'student number',
      `stu_name` varchar(50) NOT NULL COMMENT 'student name',
      PRIMARY KEY (`id`),
      KEY `idx_stu_no` (`stu_no`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
    

    参考

    【1】JPA遇到枚举类型:https://www.jianshu.com/p/9a4f0373bd19
    【2】解决JPA的枚举局限性:https://www.cnblogs.com/xiaoq/p/7885775.html

    相关文章

      网友评论

          本文标题:持久层框架JPA之枚举值处理

          本文链接:https://www.haomeiwen.com/subject/lxceldtx.html