解决存储库中一对一关系的正确方法?

时间:2019-12-11 08:11:18

标签: java spring-boot jpa

我在笔和许可证之间具有一对一的关系,现在我想在LicenseRepository中通过笔的属性(例如序列号)找到许可证。我如何在存储库中定义它,我的方法是 尝试使用命名查询进行尝试,但是当我在LicenseRepository中调用findBySerial(String serial)方法时,存在一个例外,即LicenseEntity中没有串行属性,那是正确的,但它在PenEntity中 在LicenseEntity中。我虽然那个春季靴子做了一些伏都教徒,但我意识到有一个PenEntity,其中包含一个串行属性。用Spring Boot实现此功能的正确方法是什么?

    @Repository("LicenseRepository")
    public interface LicenseRepository
            extends JpaRepository<LicenseEntity, Long>, JpaSpecificationExecutor<LicenseEntity> {

        LicenseEntity findBySerial(String serial);
        LicenseEntity findByPenId(String penId);

    }



    @AllArgsConstructor
    @Data
    @Entity
    @Table(name = "License")
    public class LicenseEntity {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "uid")
        private Long id;

        @Column(nullable = true)
        private String firstUse;

        @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        @JoinColumn(name = "pen_uid", referencedColumnName = "uid")
        private PenEntity pen;

        public LicenseEntity(PenEntity pen){
            this.pen = pen;
        }


    }


           @AllArgsConstructor
    @Data
    @NoArgsConstructor
    @Entity
    @Table(schema = "epls_dbo", name = "Pen")
    public class PenEntity {

        @Id
        @Column(name = "uid", nullable = false, unique = true)
        private Long id;

        @Column(name = "penid", nullable = false, unique = true)
        private Long penId;

        @Column(name = "penPassword")
        private String penPassword;

        @Column(nullable = false, columnDefinition = "boolean(Types#BIT)")
        boolean userLocked;

        @Column(nullable = false, columnDefinition = "boolean(Types#BIT)")
        boolean adminLocked;

        @Column(nullable = false, columnDefinition = "boolean(Types#BIT)")
        boolean gplsAccess;

        @Column( columnDefinition = "boolean(Types#BIT)")
        boolean defaultPkpAccess;

        @Column(nullable = false)
        int maxUpdateCounter;

        @Column
        byte[] symmetricKey;

        @Column
        String comment;

        @Column(nullable = false, columnDefinition = "boolean(Types#BIT)")
        boolean justActivated;

        @Column
        byte[] activationKey;

        @Column(nullable = false, columnDefinition = "penactivationstatus(Types#INTEGER)")
        int activationStatus;

        @Column(name = "serial", insertable = false, updatable = false, columnDefinition = "nvarchar(Types#NVARCHAR)")
        private String serial;

        @Enumerated(EnumType.STRING)
        PenHardware hardware;

        @Transient
        String firstUsage;


    }

1 个答案:

答案 0 :(得分:1)

您可以使用

List<LicenseEntity> findByPenSerial(String serial)

List<LicenseEntity> findByPen_Serial(String serial)

以供参考Spring Doc