2017-05-01 82 views
2

我試圖用Hibernate來實現這一目標: table relationshipJoinColumn一個外鍵

我的代碼如下:

設備型號

@Entity 
public class Device { 
@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column(nullable = false) 
private long id; 

@ManyToOne(fetch = FetchType.LAZY) 
@JoinColumn(name = "fk_user", nullable = true, referencedColumnName = "ID") 
private User user; 
... 
} 

統計模型

@Entity 
public class Statistic { 
@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column(nullable = false) 
private long id; 

@ManyToOne(fetch = FetchType.LAZY) 
@JoinColumns({ @JoinColumn(name = "fk_device", nullable = false, referencedColumnName = "ID"), 
     @JoinColumn(name = "fk_device_user", nullable = false, referencedColumnName = "fk_user") }) 
private Device device; 
... 
} 

但是,有一個錯誤說有設備中沒有邏輯列fk_user。

Caused by: org.hibernate.MappingException: Unable to find column with logical name: fk_user in device 

我想這是因爲fk_user是一個外鍵。但我該如何解決這個問題?謝謝。根據您的架構

回答

2

我將如下映射設備實體:

公共類Devince {

@ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "user_id", nullable = true) 
    private User user; 
    ... 
    } 

}

你不需要的referencedColumnName,你指的是User實體首要的關鍵。如果您要引用非主鍵列,那麼這將是必要的。

關於統計單位:

public class Statistic { 
    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumns({ @JoinColumn(name = "device_id", nullable = false), 
     @JoinColumn(name = "device_user_id", nullable = false, 
    referencedColumnName = "user_id") }) 
    ... 
    } 
} 

同樣,你只需要在第二@JoinColumnreferencesColumnName

+0

感謝您的建議。我在'@ JoinColumn'中刪除了所有第一個'referencesColumnName',但仍然收到錯誤消息'Caused by:org.hibernate.MappingException:無法在設備中查找具有邏輯名稱:user_id的列。 – Chiu