简体   繁体   中英

Removing entity from Map tries to null the reference

I have an entity Quest which contains many Task s:

@Entity
public class Quest {

    @OneToMany(orphanRemoval=true,cascade=CascadeType.ALL)
    @JoinColumn(name="quest_id")
    @MapKey(name="taskName")
    private Map<String, Task> tasks = Maps.createHash();

    @ElementCollection
    @OrderColumn
    private Set<String> completedTasks;

@Entity
public class Task implements Serializable {

    @ManyToOne(optional=false)
    @JoinColumn(name="quest_id")
    private Quest quest;

    @Column(nullable=false,updatable=false,length=50)
    private String taskName;

Now when I do this:

// store the task as completed
quest.getCompletedTasks().add(taskName); // set
// remove the task entity
quest.getTasks().remove(taskName); // map

Hibernate attempts to perform the nonsensical query, and fails:

update Task set quest_id=null where quest_id='77149'

This appears to break the connection between the quest and all its tasks ( WHERE quest_id = ... ), which seems to me like something to do when the quest itself is removed (which it isn't). In any case, it shouldn't null anything, it should just DELETE the Task entirely.

What is wrong?

The update is not nonsensical: you remove the task from quest 's list, so hibernate deletes the connection between the task and the quest .

Update: I just noticed that you have @JoinColumn and @OneToMany on the same field. I think you should do this instead (depending on which hibernate version you use):

@OneToMany(mappedBy="quest", orphanRemoval=true,cascade=CascadeType.ALL)
@MapKey(name="taskName")
private Map<String, Task> tasks = Maps.createHash();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM