Duplicate columns when using EmbeddedId with a ManyToOne mapping with Ebean

后端 未结 2 1996
暖寄归人
暖寄归人 2021-02-19 09:52

I have a model called \"EventCheckin\" which has a ManyToOne mapping to an \"Event\" and a \"User\". The PrimaryKey of the \"EventCheckin\" table is the id of the user and the i

2条回答
  •  天涯浪人
    2021-02-19 10:45

    This error occurs because columns user_id and event_id are used by composite key and at the same time they are used by @ManyToOne mappings. The solution is to add insertable = false, updatable = false attributes to @Joincolumn annotaion. Here is working code for this solution:

    EventChekin.java:

    @Entity
    @Table(name="eventCheckin")
    public class EventCheckin extends Model {
    
        public EventCheckin() {
            id = new CheckinId();
        }
    
        @EmbeddedId 
        public CheckinId id;
    
        @ManyToOne
        @MapsId("userId")
        @JoinColumn(name="user_id", insertable = false, updatable = false)
        private User user;
    
        @ManyToOne
        @MapsId("eventId")
        @JoinColumn(name="event_id", insertable = false, updatable = false)
        private Event event;
    
        public void setUser(User aUser) {
            user = aUser;
            id.userId = aUser.getId();
        }
    
        public void setEvent(Event aEvent) {
            event = aEvent;
            id.eventId = aEvent.getId();
        }
    }
    

    Checkin.java

    @Embeddable 
    public class CheckinId implements Serializable {
    
        public Long eventId;
        public String userId;
    
        @Override
        public int hashCode() {
            return eventId.intValue() + userId.length();
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj) 
                return true;
            CheckinId c = (CheckinId)obj;
            if(c==null)
            return false;
            if (c.eventId.equals(eventId) && c.userId.equals(userId)) {
                return true;
            }
            return false;
        }
    }
    

提交回复
热议问题