hi:
IN my application,I have some entities which own some collections,when I have no idea to delete them.
This is the core codes of my eneity:
Code:
@Entity
@Table(
name = "t_task")
public class Task {
private int id;
private List<TaskStep> steps = new ArrayList<TaskStep>();
public Task() {
this.createTime = new Date();
}
public Task(String name) {
this();
this.name = name;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
@OneToMany(
cascade = CascadeType.ALL)
@JoinColumn(
name = "task_id",
nullable = false)
@LazyCollection(LazyCollectionOption.FALSE)
@IndexColumn(
name = "position")
public List<TaskStep> getSteps() {
return steps;
}
// domain method
public void addSteps(TaskStep ts) {
steps.add(ts);
ts.setTask(this);
}
public void removeStep(TaskStep ts) {
steps.remove(ts);
}
// setter
public void setId(int id) {
this.id = id;
}
public void setSteps(List<TaskStep> steps) {
this.steps = steps;
for (TaskStep st : steps) {
st.setTask(this);
}
}
}
//TaskStep:
@Entity
@Table(
name = "t_taskstep")
public class TaskStep {
private int id;
private List<Operator> operator = new ArrayList<Operator>();
private Task task;
public TaskStep() {}
@Id
@GeneratedValue
public int getId() {
return id;
}
@ManyToMany(
cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
public List<Operator> getOperator() {
return operator;
}
@ManyToOne
@JoinColumn(
name = "task_id",
nullable = false,
updatable = false,
insertable = false)
public Task getTask() {
return task;
}
// domain method start
public void addOperator(Operator op) {
operator.add(op);
}
// setter
public void setId(int id) {
this.id = id;
}
public void setOperator(List<Operator> operator) {
this.operator = operator;
}
public void setTask(Task task) {
this.task = task;
}
}
//Operator:
@Entity
@Table(
name = "t_operator")
public class Operator {
private int id;
private List<TaskStep> steps = new ArrayList<TaskStep>();
public Operator() {}
@Id
@GeneratedValue
public int getId() {
return id;
}
// //setter
public void setId(int id) {
this.id = id;
}
public void setSteps(List<TaskStep> steps) {
this.steps = steps;
}
@ManyToMany(
mappedBy = "operator")
public List<TaskStep> getSteps() {
return steps;
}
}
In the db,there are tables of "t_task","t_operator","t_step","t_step_operator".
I use this manner to remove the task:
Code:
taskDao.delTaskById(5);
This is the dao:
Code:
public void delTaskById(int id) {
Task t = queryTaskById(id);
Session sess = factory.getCurrentSession();
try {
sess.beginTransaction();
sess.delete(t); // 1)
sess.flush();
sess.getTransaction().commit();
} catch (HibernateException e) {
sess.getTransaction().rollback();
}
}
I got a error which said "can not delete or update a parent row....".
Then I tried use the repalce the "
Quote:
sess.delete(t)
" to "
Quote:
sess.createQuery("delete from Task t where t.id="+id).executeUpdate()
",I got now error,but the task is not removed actually.
I have set the cascade in the mapping
What is the problem? I am going to crazy!