java - 传递的分离实体与 LatLng 列表一起保存

标签 java spring hibernate jpa

使用同一列表保存两个对象时出现错误: 而且我不太了解每个类的 CascadeType 和 GenerationType。

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: 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 对象可能属于多个 GeoArea 对象,因此关系应该是 @ManyToMany 而不是 @一对多

关于java - 传递的分离实体与 LatLng 列表一起保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58856929/

相关文章:

java - 使用 Class.this.field = value 在构造函数中初始化最终字段会出错,而使用 this.field = value 则不会

java - 自 Spring Boot 2.0.2-RELEASE 以来,指标端点不可用

java - 如何分离与@SpringBootApplication注释的类不同的类中的bean

mysql - Spring Data JPA 方法命名包含双值查询

JavaPreparedStatement 在 SQL 查询中将小写字符串名称传递给区分大小写的 PostgreSQL 数据库

java - 为 Eclipse 项目设置日志记录配置文件

java - 使用 JPQL 的 createQuery 挂起

java - 带 hibernate 注解的模式导出

java - 了解 Android 中的 Runnable

javax.validation.NotBlank 缺少 validator