传递的分离实体与LatLng列表一起保留

在保存两个具有相同列表的对象时出现错误: 而且我不太了解每个类的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);
    }

如果您有任何想法:)

谢谢:)

xzj700106 回答:传递的分离实体与LatLng列表一起保留

很有可能GeoAreaService#create方法不在事务内运行,因此LatLng返回的latLngRepository对象是分离的。通过添加@Transactional批注(https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/data-access.html#transaction-declarative),尝试使该方法具有事务性。

此外,由于相同的LatLng对象可能属于多个GeoArea对象,因此关系应为@ManyToMany而不是@OneToMany

本文链接:https://www.f2er.com/3102593.html

大家都在问