Pergunta

I am a bit confused as I can't force Hibernate to remove the rows in the joining table. Probably I need to configure something differently.

I have a table Component and Task and a table the connects them Component_Tasks. In my class Component I have:

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Component_Tasks",
           joinColumns = @JoinColumn(name = "ComponentID"), inverseJoinColumns = @JoinColumn(name = "TaskID"))
public List<Task> getTasks() {
    return tasks;
}

and in my class Task I have

@ManyToOne
@JoinColumn(name = "ComponentID")
public Component getComponent() {
    return component;
}

What I want is that when I delete the a task I delete the underlining row in the Component_Tasks table by default. Basically my delete fails because of foreign key relationship

ALTER TABLE Component_Tasks ADD FOREIGN KEY (TASKID)  REFERENCES Tasks (ID); 

I believe that I can achieve the same behaviour if I set the component in the task to null and then I save the object and then try to delete it. But I want Hibernate to do this by default.

Any suggestions?

Foi útil?

Solução

Your mapping is wrong. In Component, you're saying that the association between Component and Task is mapped by a join table.

And in Task, you're saying that the same association is mapped by a join column in the Task table.

Make up your mind. If the association is a OneToMany bidirectional association, a join table is usually not necessary, and you just need

@OneToMany(cascade = CascadeType.ALL, mappedBy = "component")
public List<Task> getTasks() {
    return tasks;
}

and

@ManyToOne
@JoinColumn(name = "ComponentID")
public Component getComponent() {
    return component;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top