传递给持久化的java分离实体,包含LatLng列表
保存具有相同列表的两个对象时出错: 我不太了解每个类的cascade类型和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);
}
如果你有任何想法:)
谢谢:)
# 1 楼答案
很可能
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
,而不是@OneToMany