Duplicate columns when using EmbeddedId with a ManyToOne mapping with Ebean

≡放荡痞女 提交于 2019-12-03 23:34:37

It looks like you try to do same thing via @MapsId and @EmbeddedId. One (working) option is to go for IdClass (equals, hashcode, extra attributes etc are cut away):

    @Entity
    public class User {
        @Id public String id;
    }

    @Entity
    public class Event {
        @Id public long id;
    }

    public class CheckinId implements Serializable {
        public Long event;
        public String user;
    }

    @Entity
    @IdClass(CheckinId.class)
    @Table(name="eventCheckin")
    public class EventCheckin {

        @Id
        @JoinColumn(name="user_id")
        @ManyToOne public User user;

        @Id
        @JoinColumn(name="event_id")
        @ManyToOne public Event event;
    }
rtruszk

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!