Ebean EmbeddedId mapping column to ManyToOne relation

后端 未结 1 471
無奈伤痛
無奈伤痛 2021-01-15 05:36

I\'m facing a problem with Ebean when trying to create Composed Keys (EmbeddedId).

This is a draft of what I have:

@Entity public class EntityA exten         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-15 06:30

    To solve this problem we have to:

    1. Map EntityB.entityA to the same column as EntityB.ID.entityA_FK_ID
    2. set 'insertable' and 'updateable' attributes of EntityB.entityA @JoinColumn annotation
    3. Override setter of EntityB.entityA

    Here is the code:

    EntityA.java:

    @Entity 
    public class EntityA extends Model {
        @Id
        private String ID;
    
        @OneToMany(mappedBy="entityA")
        public List listEntitesB; 
    
        public static Finder find = new Finder(
            String.class, EntityA.class
        ); 
    
        public EntityA() {
            ID = UUID.randomUUID().toString();
        }
    
        public String getID() {
            return ID;
        }
    }
    

    EntityB.java:

    @Entity 
    public class EntityB extends Model {
    
        @EmbeddedId
        private EntityB_PK ID;
    
        @ManyToOne
        @JoinColumn(name = "entityA_fk_id", insertable = false, updatable = false)
        private EntityA entityA; 
    
        public EntityA getEntityA() {
            return entityA;
        }
    
        public void setEntityA(EntityA aEntityA) {
            entityA = aEntityA;
            ID.entityA_FK_ID = aEntityA.getID();
        }
    
        public EntityB(String entityB_ID){
             ID = new EntityB_PK(UUID.randomUUID().toString(), entityB_ID);
        }
    
        public String getID() {
            return ID.entityB_ID;
        }
    }
    

    EntityB_PK.java:

    @Embeddable 
    public class EntityB_PK implements Serializable {
    
        public String entityB_ID;
    
        @Column(name="entityA_fk_id")
        public String entityA_FK_ID;
    
        public EntityB_PK(String entB_ID, String entA_FK_ID){
           entityB_ID = entB_ID;
           entityA_FK_ID = entA_FK_ID;
        } 
    
        @Override
        public int hashCode() {
            return entityB_ID.length() + entityA_FK_ID.length();
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj) 
                return true;
            EntityB_PK b = (EntityB_PK)obj;
            if(b==null)
                return false;
            if (b.entityB_ID.equals(entityB_ID) && b.entityA_FK_ID.equals(entityA_FK_ID)) {
                return true;
            }
            return false;
        }
    }
    

    0 讨论(0)
提交回复
热议问题