我想要做的是加入一個表到另一個表基於用戶ID。玩框架加入表
我有一個用戶表和一個警報歷史記錄表,其中有一個外鍵與用戶的ID相關聯。
我使用由Netbeans 7.4生成的實體。
用戶:
@Entity
@Table(name = "Users", schema = "dbo")
public class User extends Model implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "UserID")
private Integer userID;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "userId")
private Collection<AlertHistory> alertHistoryCollection;
{ ... }
警報歷史記錄:
@Entity
@Table(name = "Alert_History", schema = "dbo")
public class AlertHistory extends Model implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;
@Basic(optional = false)
@Column(name = "user_id")
@ManyToOne(fetch = FetchType.EAGER)
private int userId;
@Basic(optional = false)
@Column(name = "message_id")
private long messageId;
@Basic(optional = false)
@Lob
@Column(name = "alerts_triggered")
private String alertsTriggered;
{...}
我期望的是,當我打開一個用戶,它會嘗試加入基於該用戶id的AlertsHistory
表結果。然而,在運行時,AlertsHistory
集合總是null
更新:解決
我一直在尋找這個錯誤的方式。爲了做一個JOIN,AlertHistory希望交給一個用戶對象,而不僅僅是userId鍵。添加User
場到AlertHistory
模式,並改變@OneToMany(mappedBy = "userId")
到@OneToMany(mappedBy = "user"
,然後在AlertHistory
加入@JoinColumn(name="user_id", referencedColumnName="userId") private User user;
到User
場讓我整理出來!感謝大家的幫助。
應該不是atributte「私人int userId「在AlertHistory是」私人用戶userId「? – edubriguenti
謝謝@edubriguenti,那是棺材裏的釘子!我看着這一切都是錯誤的。當我真的需要簡單地引用整個對象時,我想我需要傳遞鍵(userId)。這讓我陷入了另一個問題,因爲JPA推斷爲匹配的列(即它正在尋找名爲user_userId的列當然不存在)。 解決方案有以下內容添加到'AlertHistory': '@JoinColumn(name =「user_id」,referencedColumnName =「userId」) 私人用戶用戶;' –