簡體   English   中英

Hibernate中的@ManyToOne映射不起作用

[英]@ManyToOne mapping in Hibernate not working

我有兩個類,具有多對一映射的InviteEvent :一個事件有很多邀請。 以下是帶有Hibernate批注的相關代碼片段/ SQL:

db.Events

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| event_id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255) | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

db.Invites

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| invite_id | int(11)      | NO   | PRI | NULL    | auto_increment |
| name      | varchar(255) | YES  |     | NULL    |                |
| event_fk  | int(11)      | NO   | MUL | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

DbInvite.java

@ManyToOne
private DbEvent event;

public DbInvite() {
}

public DbInvite(String name, DbEvent event) {
    this.name = name;
    this.event = event;
}

// getters and setters

DbEvent.java

@OneToMany(mappedBy = "event")
private Set<DbInvite> invites;

public DbEvent() {
}

public DbEvent(String name) {
    this.name = name;
}

// getters and setters

最后,我-這就是大多數Hibernate示例似乎停止的地方-我以以下方式創建實例:

DbEvent dbEvent = new DbEvent(name);
DbInvite dbInvite = new DbInvite(name, dbEvent);

我收到的錯誤是:

org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'event_event_id' in 'field list'

我要去哪里錯了? 當主鍵明顯是event_id時, event_event_id會從哪里來?

您需要為多對一指定連接列,否則JPA / Hibernate將采用默認值。

當您這樣做時:

DbEvent dbEvent = new DbEvent(name);
//the id is setted in when persist into the db
dbEvent = someMethodThatPersistInDb(dbEvent);
//now the object have the id created in the db now insert the other one
DbInvite dbInvite = new DbInvite(name, dbEvent);
someMethodThatPersistInDb(dbInvite); 

我希望可以為您提供幫助,也許您可​​以發布其余的映射類以檢查代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM