我試圖創建兩個實體(公民,城鎮)之間的關係。
一個公民連接到一個城鎮,一個城鎮可以有幾個公民。
我不知道什麼樣的關係是好的。彈簧數據:設置兩個實體之間的關係
我已經試過了:
@Entity
@Table(name = "citizen")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Citizen implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "lastname", nullable = false)
private String lastname;
@OneToOne
@JoinColumn
private Town ownTown;
//getter and setter
}
@Entity
@Table(name = "town")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Town implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "town_name", nullable = false)
private String townName;
//getter and setter
}
,但我得到一個
產生的原因: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:爲 重複條目 '1'鍵'town_id'
當我嘗試插入一個公民。
這種關係有什麼問題?