Hibernate - 使用自动FK

时间:2018-05-21 22:00:09

标签: java hibernate

我对ManyToSomething关系有疑问。我无法制作能够正确生成FK的注释。也许整个想法都很糟糕(例如只持有一个实体级联)。

让我们在程序的某个地方有这个简化的代码:

    Conversation conversation = new Conversation(){{
        getMessages().add(new Message());
    }};

    session.persist(conversation);

    // OR LIKE THIS:

    Message message = new Message();     
    Conversation conversation = new Conversation();

    message.setConversation(conversation);

    session.persist(message);

然后简化Hibernate注释:

@Entity
public class Message{

  @Id
  @GeneratedValue
  private int id;

  @ManyToOne
  private Conversation conversation;

}

@Entity
public class Conversation{

  @Id
  @GeneratedValue
  private int id;

  @OneToMany(mappedBy = "conversation", cascade = CascadeType.PERSIST)
  private Set<Message> messages = new HashSet<Message>();

  public Set<Message> getMessages() {
    return messages;
  }
}

因此,对话的FK应该保存在Message(One Conversation - Many Messages)中。但是当Java代码运行时,数据库只会在Conversation端写入新ID,而不会写入FK。怎么可能?

更新1(仍然没有运气):

@Entity
@Table(name = "conversation_message")
public class Message{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private int id;

    @ManyToOne
    @JoinColumn(name = "conversation_id", insertable = false, updatable = false)
    private Conversation conversation;

... (other fields + getters/setters without annotation)
}

@Entity
public class Conversation{ 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private int id;

    @OneToMany(mappedBy = "conversation", cascade = CascadeType.PERSIST)
    private Set<Message> messages = new HashSet<Message>();

... (other fields + getters/setters without annotation)
}

更新2(使用UPDATE 1 Annotation),在此:

Conversation conversation = new Conversation();
conversation.getMessages().add(new Message(){{
    setConversation(conversation);
    setText("test");
}});

session.persist(conversation);

休眠日志:

insert 
        into
            conversation
            (course_id, created, name, replies, user_id) 
        values
            (null, null, null, true, null)

insert 
        into
            conversation_message
            (file, sent, text) // There is missing conversation_id at all
        values
            (null, null, "Test")

1 个答案:

答案 0 :(得分:0)

我在代码中看不到任何Id字段... 您可能缺少的是:

private Integer id;  

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

然后它会在持久时自动生成。

更新: 同样要在表Messages中使用外键,您需要:

@JoinColumn(name = "conversation_id", insertable = false, updatable = false)
@ManyToOne
private Conversation conversation;