我有一個City
實體和Person
實體。我想建立一個從Person到City的OneToMany
關係,表明一個人居住在哪個城市。它是Person的單向OneToMany關係。獨特contraint違反了一對多的關係
我的城市類看起來像這樣
@Entity
public class City {
@Id
@GeneratedValue
private Long id;
private String name;
...
}
Person實體看起來像這樣
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(fetch = FetchType.EAGER, orphanRemoval = true)
private Set<City> livedInCities = new HashSet<City>();
...
}
在我的測試,我只是先創建一個城市並保存它。然後創建一個人並在保存該人之前添加保存的城市實例。保存完人後,一切都很好。
當我添加第二個人,並添加同一個城市的第二個人,它拋出一個違反唯一約束。我不知道爲什麼會這樣,因爲在關係表中,這應該是2人,市1 測試代碼
@Test
public void test() {
City chicago = new City();
chicago.setName("chicago");
City savedChicago = cityRepo.save(chicago);
Person john = new Person();
john.setName("john");
john.addCity(savedChicago);
Person savedJohn = personRepo.save(john);
Person tom = new Person();
tom.setName("tom");
tom.addCity(savedChicago);
Person savedTom = personRepo.save(tom);
System.out.println(savedTom);
System.out.println(savedJohn);
}
2015-07-02 18:11:21.026 WARN 5473 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 23505, SQLState: 23505 2015-07-02 18:11:21.026 ERROR 5473 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Unique index or primary key violation: "UK_B6XKGKBT91IXB0WE6N030RFPQ_INDEX_C ON PUBLIC.PERSON_LIVED_IN_CITIES(LIVED_IN_CITIES_ID) VALUES (1, 1)"; SQL statement:
完整的項目插入一個新行這可在 https://github.com/adeelmahmood/jpatest-onetomany
我希望得到任何幫助。
你不必這裏'@ OneToMany'關係,而是一個'@ ManyToMany'因爲每個人都可能已經住在不止一個城市,每個城市可能有一個以上的人住過。 – manish