[英]Detached entity passed to persist with List of LatLng
使用相同的列表保存兩個 object 時出現錯誤:而且我不太了解每個類的 CascadeType 和 GenerationType。
引起:org.hibernate.PersistentObjectException:分離的實體傳遞給堅持:LatLng
考試:
@Test
void testGetGeoArea() throws Exception {
GeoArea geoArea = new GeoArea();
GeoArea geoArea2 = new GeoArea();
List<LatLng> shape = Arrays.asList(
new LatLng(1,1),
new LatLng(2,2),
new LatLng(3,3));
geoArea.setShape(shape);
geoArea2.setShape(shape);
geoAreaService.create(geoArea);
geoAreaService.create(geoArea2);
實體:
@Table(
uniqueConstraints=
@UniqueConstraint(columnNames={"LATITUDE", "LONGITUDE"})
)
@Entity
public class LatLng implements Serializable {
@Id
@Column(name="LATLNG_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="LATITUDE")
private double latitude;
@Column(name="LONGITUDE")
private double longitude;
@Entity
@Table(name = "GEO_AREA")
public class GeoArea implements GeoData {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name="AREA_ID")
private Long id;
@Column(name="NAME")
private String name;
@OneToMany(cascade = CascadeType.PERSIST)
private List<LatLng> shape;
創建實體的服務:
@Override
public GeoArea create(GeoArea geoArea) {
geoArea.setShape(geoArea.getShape().stream()
.map(p -> {
LatLng persisted = latLngRepository.findByCoordinates(p.getLatitude(), p.getLongitude());
if(persisted != null){
return persisted;
}
return p;
})
.collect(Collectors.toList()));
return geoAreaRepository.save(geoArea);
}
如果你有任何想法:)
謝謝:)
很可能GeoAreaService#create
方法沒有在事務中運行,因此latLngRepository
返回的LatLng
對象被分離。 嘗試通過添加 @Transactional 注釋( https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/data-access.html#transaction-declarative )使該方法具有事務性。
此外,由於同一個LatLng
object 可能屬於多個GeoArea
對象,因此關系應該是@ManyToMany
而不是@OneToMany
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.