2015-09-29 33 views
0

我遇到了一個用戶類和汽車類的情況。 和我的mysql數據庫中的表可能看起來像這樣 下面是我如何想象這兩個實體之間的關係的草圖。如何正確構造兩個類之間的休眠關係

   user       user_car     car 
username firstname lastname <----> username car_id <----> car_id cartype 
    tea  bruce  anderson   tea  1    1  ford123 
    t   arnold  mena    tea  2    2  audio2 
              t   2 

用戶有一個Set,其中包含汽車的對象。但汽車不應該引用任何用戶。我已經嘗試了幾種方法,但總是以「重複鍵」爲主的相同錯誤結束。

@Entity 
public class car { 
@Id 
@GeneratedValue(strategy=GenerationType.AUTO) 
private long car_id; 
    private String type; 

public car(){ 

} 

public long getCar_id() { 
    return car_id; 
} 

public void setCar_id(long car_id) { 
    this.car_id = car_id; 
} 

public String getType() { 
    return type; 
} 

public void setType(String type) { 
    this.type = type; 
} 

}

用戶類

@Entity 
public class userr { 

    @Id 
    private String username; 
    private String firstname; 
    private String lastname; 

    //Some relation here, which I do not know how to properly set up 
    private Set<Car> cars = new HashSet<>(); 

    public userr(){ 

    } 

    public String getUsername() { 
     return username; 
    } 

    public void setUsername(String username) { 
     this.username = username; 
    } 

    public String getFirstname() { 
     return firstname; 
    } 

    public void setFirstname(String firstname) { 
     this.firstname = firstname; 
    } 

    public String getLastname() { 
     return lastname; 
    } 

    public void setLastname(String lastname) { 
     this.lastname = lastname; 
    } 

    public Set<Car> getCars() { 
     return cars; 
    } 

    public void setCars(Set<Car> cars) { 
     this.cars = cars; 
    } 
} 

任何幫助感激。

回答

1

您應該使用連接表進行多對多映射。在Hibernate文檔中查看它。

+0

如果我使用帶有Jay和@ManyToMany的代碼,當嘗試插入另一輛汽車時仍然出現重複錯誤。 – JonCode

1

在您的實體上使用下面的映射。

@OneToMany 
    @JoinTable(
      name="USER_CAR", 
      joinColumns = @JoinColumn(name="username"), 
      inverseJoinColumns = @JoinColumn(name="car_id") 
    ) 
private Set<Car> cars = new HashSet<>();  
+0

我嘗試了上面的內容,並添加了id爲1的汽車,該汽車成功進入了我的數據庫。在我嘗試將另一輛帶有id 3的汽車嘗試給同一個用戶之後。但我仍然得到重複'茶-1'的關鍵'PRIMARY'是我的冬眠試圖插入雙行?因爲說dublicate key 1似乎很奇怪,所以當我嘗試插入一輛id爲3的汽車時 – JonCode

+0

@JonCode用你的實際代碼更新帖子以獲得更好的答案。 – alamar

0

看起來我固定它,通過創建在jointable第三列,其自動遞增和工作原理的主鍵。但是現在它將所有內容插入兩次以上。如果有人知道一個簡單的解決方法,我會傾聽它。