如何使用Hibernate从表中删除相关记录

时间:2012-06-21 22:14:42

标签: hibernate

我正在做一个我继承的项目,我遇到了一些麻烦。在我的数据库中,我有一个传感器表。传感器可以负责任务,我有一个任务表。除非传感器有任务,否则我可以添加和删除传感器。一旦传感器被赋值,我就会得到一个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;

1 个答案:

答案 0 :(得分: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并没有意义:当您删除其中一个任务时,您不想删除传感器。