0

我正在做一个我继承的项目,但遇到了一些麻烦。在我的数据库中,我有一个传感器表。传感器可以分配任务,我有一个任务表。我可以添加和删除传感器,除非传感器被分配了任务。传感器完成任务后,我会收到 ConstraintViolationException。任务实体保留对传感器对象的引用,我确定问题出在某处。我只想能够使用我的传感器 DAO 对象来删除传感器并让它自动删除所有关联的任务。我正在摸索这个,我猜我需要在我的传感器类中添加某种级联注释,但我不确定。这是我所拥有的:

    @Entity
@Table(name = "sensors")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class Sensor {
    @Id
    @Column(name = "sensor_id")
    private String sensorId;
    @Column(name = "obs_area_wkt", length = 2048)
    private String observableAreaWKT;
    @Column(name = "tasking_provider")
    private String taskingProvider;
    @Column(name = "delivery_uri")
    private String deliveryUri;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "data_service_id")
    private DataService dataService;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "sensor_description")
    private SensorDescription sensorDescription;
    @Column(name = "observable_property")
    private String observableProperty;

这是任务对象:

@Entity
@Table(name = "tasks")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class Task {    
@Id
    @Column(name = "task_id", length=276)
    private String id;

    @ManyToOne(cascade = CascadeType.ALL)
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    @JoinColumn(name ="sensor")
    private Sensor sensor;

    @Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
    @Column(name = "recieved")
    private DateTime received;

    @Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
    @Column(name = "executed")
    private DateTime executed;

    @Column(name = "command_text")
    @Lob
    private String commandText;

    @Column(name = "task_parameters")
    @Lob
    private String taskParameters;

    @Column(name = "status")
    private String status;

    @Column(name = "request_status")
    private String requestStatus;

    @Column(name = "user_id")
    private String userId;

    @Column(name = "group_id")
    private String groupId;
4

1 回答 1

2

在删除传感器时,使关联双向并添加级联以删除传感器的任务:

@OneToMany(mappedBy = "sensor", cascade = CacsadeType.REMOVE)
private Set<Task> tasks;

或者,在删除传感器之前,先搜索其所有任务并删除它们:

List<Task> tasks = 
    session.createQuery("select task from Task task where task.sensor = :sensor")
           .setParameter("sensor", sensor)
           .list();
for (Task task : tasks) {
    session.delete(task);
}
session.delete(sensor);

请注意,将 cascade = ALL 设置为从任务到传感器的 ManyToOne 没有任何意义:您不想在删除其中一项任务时删除传感器。

于 2012-06-21T22:21:56.320 回答