2012-06-21 85 views
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; 

回答

2

要麼使協會的雙向和刪除傳感器時添加級聯remoe傳感器的任務:

@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沒有任何意義:您不希望在刪除其中一個任務時刪除傳感器。

+0

你是男人:) – Bal