Hibernate映射理解

Hibernate Mapping Understanding

我在了解 hibernate 如何映射集合双向时遇到了一点问题。

通缉如下: 表架构:

事件(e_id,日期,i_id)

信息 (i_id, detailDesc)

我有多个事件和一些信息对象,它们汇总了 x 个事件的详细信息。作为对象,我有不同的事件对象和一些应该包含事件对象列表的信息对象。与信息对象相关的事件对象应该关联一个信息对象,请参阅下面的 class 信息。

@Entity
@Table(name = "info")
public class Info {
    @Id
    @GenericGenerator(name = "gen", strategy = "increment")
    @GeneratedValue(generator = "gen")
    @Column(name = "i_id")
    private long id;

    @JoinTable(name = "events",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "i_id"))
    @OneToMany(targetEntity = Event.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Event> events;

    String detailDesc;

}


@Entity
    @Table(name = "event") 
    public class Event {
        @Id
        @GenericGenerator(name = "gen", strategy = "increment")
        @GeneratedValue(generator = "gen")
        @Column(name = "e_id")
        private long id;

        // Can be NULL 
        @ManyToOne(targetEntity = Info.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL, optional = true)
        @JoinColumn(name = "i_id")
        private Info info;

       private Date date;

    }

就像现在一样,hibernate 说重复输入或外键约束失败 (event, CONSTRAINT FK_r9sdjn6nelyo5be86vu0b2prs FOREIGN KEY (e_id) REFERENCES info (i_id))

您的映射不正确。鉴于您的架构,您没有使用 JoinTable 因此因此在 @ManyToOne 侧设置 @JoinColumn (如您所用)并在反面简单地使用 'mappedBy' 。确保关系的双方都设置为确保级联按预期工作。

如果您确实想使用联接 table(而不是来自事件 > 信息的 FK),那么您可以将现有的 @JoinTable 移动到 @ManyToOne 并删除 @JoinColumn。无论你使用@JoinTable 还是@JoinColumn,反面都会保持如下。

@Entity
@Table(name = "info")
public class Info {

    @Id
    @GenericGenerator(name = "gen", strategy = "increment")
    @GeneratedValue(generator = "gen")
    @Column(name = "i_id")
    private long id;


    @OneToMany(mappedBy="info" cascade = CascadeType.ALL)
    private List<Event> events;

    String detailDesc;

    //set both sides of the relationship
    public void addEvent(Event event){
        event.setInfo(this);
        events.add(event);
    }

    public List<Event> getEvents(){
        //return unmodifiable list or iterator to force clients through addEvent() method
    }

}


@Entity
@Table(name = "event") 
 public class Event {
    @Id
    @GenericGenerator(name = "gen", strategy = "increment")
    @GeneratedValue(generator = "gen")
    @Column(name = "e_id")
    private long id;

    @ManyToOne(cascade = CascadeType.ALL, optional = true)
    @JoinColumn(name = "i_id")
    private Info info;

   private Date date;

 }