Я пытаюсь сохранить членов класса, BorderPoint.После сохранения определенного количества объектов openJPA выдает следующее исключение:
[ERROR] org.apache.openjpa.persistence.ArgumentException: Попытка присвоить идентификатор "0" новому экземпляру "org.jason.mapmaker.shared.model.BorderPoint@3134a2 "не удалось;в кеше L1 уже есть объект с этим идентификатором.Вы должны удалить этот объект (в предыдущей или текущей транзакции) перед повторным использованием его идентификатора.Эта ошибка также может возникать, когда классы с горизонтальным или вертикальным отображением используют идентификатор приложения с автоматическим приращением и не используют иерархию классов идентификаторов приложения.
Метод для сохранения значений BorderPoints принимает список объектов BorderPoint и пытается выполнитьразбить упорство на партии.Вот код:
public void persistList(List<BorderPoint> objectList) throws RepositoryException {
EntityManager em = entityManagerFactory.createEntityManager();
try {
em.getTransaction().begin();
int i = 1;
for (BorderPoint bp : objectList) {
em.persist(bp);
if (i % 100 == 0) {
em.flush();
em.clear();
}
i++;
}
em.getTransaction().commit();
} catch (EntityExistsException ex) {
// need to log this somehow
//log.warning("persist() threw EntityExistsException: " + ex.getMessage());
ex.printStackTrace();
throw new RepositoryException(ex);
}
catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
Просто для полноты, вот метод вызова:
/**
* Cycle through and save the borderpoints saved in the Shapefile's geometry
*
* @param featureCollection
* @throws ServiceException
*/
private void saveBorderPoints(FeatureCollection featureCollection) throws ServiceException {
FeatureIterator iterator = featureCollection.features();
while (iterator.hasNext()) {
SimpleFeatureImpl feature = (SimpleFeatureImpl) iterator.next();
String geoId = (String) feature.getAttribute("GEOID10");
Location location = locationRepository.getByGeoId(geoId);
if (location == null) {
throw new ServiceException("saveBorderPoints() threw ServiceException due to null Location");
}
MultiPolygon multiPolygon = (MultiPolygon) feature.getDefaultGeometry();
Geometry geometry = multiPolygon.getBoundary();
// Create the result list. Set initial capacity size to number of actual points in the geometry to avoid some
// overhead when dealing with the list
List<BorderPoint> borderPointList = new ArrayList<BorderPoint>(geometry.getNumPoints());
// cycle through the coordinates to create the border points
Coordinate[] coordinates = geometry.getCoordinates();
for (Coordinate c : coordinates) {
BorderPoint borderPoint = new BorderPoint();
borderPoint.setLocation(location);
borderPoint.setLng(new BigDecimal(c.x));
borderPoint.setLat(new BigDecimal(c.y));
borderPointList.add(borderPoint);
}
try {
borderPointRepository.persistList(borderPointList);
} catch (RepositoryException e) {
throw new ServiceException("saveBorderPoints() threw RepositoryException", e);
}
}
iterator.close();
}
Есть идеи?
РЕДАКТИРОВАТЬ:
Вот класс BorderPoint, согласно запросу:
@Entity
@Table(name = "BORDERPOINT")
public class BorderPoint implements Serializable {
private Long id;
private Location location;
private BigDecimal lat;
private BigDecimal lng;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="LAT")
public BigDecimal getLat() {
return lat;
}
public void setLat(BigDecimal lat) {
this.lat = lat;
}
@Column(name="LNG")
public BigDecimal getLng() {
return lng;
}
public void setLng(BigDecimal lng) {
this.lng = lng;
}
@ManyToOne(cascade = CascadeType.ALL, targetEntity = Location.class)
@JoinColumn(name="LOCATIONID")
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}