2016-04-01 70 views
0

我試圖創建兩個實體(公民,城鎮)之間的關係。
一個公民連接到一個城鎮,一個城鎮可以有幾個公民。
我不知道什麼樣的關係是好的。彈簧數據:設置兩個實體之間的關係

我已經試過了:

@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'

當我嘗試插入一個公民。

這種關係有什麼問題?

回答

0
@Entity 
public class Citizen implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @ManyToOne 
    @JoinColumn(name = "town_id", referencedColumnName = "id") 
    private Town town; 

//getter and setter 
} 


@Entity 
public class Town implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @OneToMany(mappedBy = town) 
    private List<Citizen> citizens; 

//getter and setter 
} 
0

一個城鎮有很多公民。這是一對多的關係。

  • 用TownId創建鎮表。
  • 創建一個公民表並將TownId引用爲城鎮表上述步驟中的外鍵。這樣,你可以指定許多公民在一個城鎮。

  • 以下是SpringData中的多對一關係example。這個A狗窩(用戶)的例子可以有多個狗。根據您的需要定製它。

相關問題