title: How to delete dependent records from a table with Hibernate
body: <p>I'm working on a project I inherited and I'm having some trouble.  In my database, I have a table for sensors.  The sensors can be tasked, and I have a table for tasks.  I can add and remove sensors, unless the sensor is tasked.  Once the sensor is tasked, I get a ConstraintViolationException.  The task entity keeps a reference to the sensor object and I'm sure the problem lies somewhere there.  I want to just be able to use my sensor DAO object to delete the sensor and have it automatically delete all of the associated tasks.  I'm fumbling my way through this and I'm guessing I need to add some sort of cascade annotation to my sensors class, but I'm not sure.  Here's what I have:</p>
  
  <pre><code>    @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;
  </code></pre>
  
  <p>and here is the task object:</p>
  
  <pre><code>@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;
  </code></pre>