簡體   English   中英

傳遞的分離實體與 LatLng 列表保持一致

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM