如何在Hibernate中从联接表中删除记录

3

论坛成员

我需要大家的帮助。我有两个POJO模型,它们之间是一对多的关系。 我的项目POJO如下所示:

@Entity
@Table(name = "project")
public class Project implements java.io.Serializable {

    private Integer projectid;
    private Date enddate;
    private String projectdesc;
    private String projectname;
    private String projecttitle;
    private Date startdate;
    private Set<Task> tasks = new HashSet<Task>(0);

    public Project() {
    }

    public Project (Integer id,String projectname, String projecttitle, String projectdesc, Date startdate, Date enddate) {
        this.projectid = id;
        this.enddate = enddate;
        this.projectdesc = projectdesc;
        this.projectname = projectname;
        this.projecttitle = projecttitle;
        this.startdate = startdate;
    }

    public Project(Date enddate, String projectdesc, String projectname,
            String projecttitle, Date startdate, Set<Task> tasks) {
        this.enddate = enddate;
        this.projectdesc = projectdesc;
        this.projectname = projectname;
        this.projecttitle = projecttitle;
        this.startdate = startdate;
        this.tasks = tasks;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "projectid", unique = true, nullable = false)
    public Integer getProjectid() {
        return projectid;
    }

    public void setProjectid(Integer projectid) {
        this.projectid = projectid;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "enddate", length = 19)
    public Date getEnddate() {
        return enddate;
    }

    public void setEnddate(Date enddate) {
        this.enddate = enddate;
    }

    @Column(name = "projectdesc")
    public String getProjectdesc() {
        return projectdesc;
    }

    public void setProjectdesc(String projectdesc) {
        this.projectdesc = projectdesc;
    }

    @Column(name = "projectname")
    public String getProjectname() {
        return projectname;
    }

    public void setProjectname(String projectname) {
        this.projectname = projectname;
    }

    @Column(name = "projecttitle")
    public String getProjecttitle() {
        return projecttitle;
    }

    public void setProjecttitle(String projecttitle) {
        this.projecttitle = projecttitle;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "startdate", length = 19)
    public Date getStartdate() {
        return startdate;
    }

    public void setStartdate(Date startdate) {
        this.startdate = startdate;
    }

    @OneToMany(cascade = CascadeType.ALL, fetch =FetchType.EAGER)
    @JoinTable(name = "project_task", joinColumns = { @JoinColumn(name = "projectid") }, inverseJoinColumns = { @JoinColumn(name = "taskid") })
    public Set<Task> getTasks() {
        return tasks;
    }

    public void setTasks(Set<Task> tasks) {
        this.tasks = tasks;
    }


}

我的任务POJO是:

@Entity
@Table(name = "task")
public class Task implements java.io.Serializable {

    private Integer taskid;
    private Integer depth;
    private Double duration;
    private String durationunit;
    private Date enddate;
    private Integer parentid;
    private Integer percentdone;
    private Integer priority;
    private Date startdate;
    private Integer taskindex;
    private String taskname;

    public Task() {
    }

    public Task(Integer depth, Double duration, String durationunit,
            Date enddate, Integer parentid, Integer percentdone,
            Integer priority, Date startdate, Integer taskindex,
            String taskname) {
        this.depth = depth;
        this.duration = duration;
        this.durationunit = durationunit;
        this.enddate = enddate;
        this.parentid = parentid;
        this.percentdone = percentdone;
        this.priority = priority;
        this.startdate = startdate;
        this.taskindex = taskindex;
        this.taskname = taskname;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "taskid", unique = true, nullable = false)
    public Integer getTaskid() {
        return taskid;
    }

    public void setTaskid(Integer taskid) {
        this.taskid = taskid;
    }

    @Column(name = "depth")
    public Integer getDepth() {
        return depth;
    }

    public void setDepth(Integer depth) {
        this.depth = depth;
    }

    @Column(name = "duration", precision = 22, scale = 0)
    public Double getDuration() {
        return duration;
    }

    public void setDuration(Double duration) {
        this.duration = duration;
    }

    @Column(name = "durationunit")
    public String getDurationunit() {
        return durationunit;
    }

    public void setDurationunit(String durationunit) {
        this.durationunit = durationunit;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "enddate", length = 19)
    public Date getEnddate() {
        return enddate;
    }

    public void setEnddate(Date enddate) {
        this.enddate = enddate;
    }

    @Column(name = "parentid")
    public Integer getParentid() {
        return parentid;
    }

    public void setParentid(Integer parentid) {
        this.parentid = parentid;
    }

    @Column(name = "percentdone")   
    public Integer getPercentdone() {
        return percentdone;
    }

    public void setPercentdone(Integer percentdone) {
        this.percentdone = percentdone;
    }

    @Column(name = "priority")
    public Integer getPriority() {
        return priority;
    }

    public void setPriority(Integer priority) {
        this.priority = priority;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "startdate", length = 19)
    public Date getStartdate() {
        return startdate;
    }

    public void setStartdate(Date startdate) {
        this.startdate = startdate;
    }

    @Column(name = "taskindex")
    public Integer getTaskindex() {
        return taskindex;
    }

    public void setTaskindex(Integer taskindex) {
        this.taskindex = taskindex;
    }

    @Column(name = "taskname")
    public String getTaskname() {
        return taskname;
    }

    public void setTaskname(String taskname) {
        this.taskname = taskname;
    }


}

该项目的POJO与任务之间存在一对多的关系。现在我想根据传递的ID删除一个任务,但问题是我无法删除联接表project_task的外键。

我尝试使用以下代码先删除project_task:

Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("delete from project_task where taskid="+id);
        query.executeUpdate();

然后我尝试使用以下代码删除任务。
Object record = hibernateTemplate.load(Task.class, id);
hibernateTemplate.delete(record);

但是不知道为什么这里删除没有发生。有没有人知道我在代码中做错了什么导致删除无法发生

你使用联接表来处理一对多关系,而不是在任务方面使用外键,有特别的原因吗? - Sebastien
我只想让我的数据库保持干净。我的project_task表将管理项目和任务之间的所有关系。一个项目ID在project_task表中与多个任务ID相关联。现在一切都正常工作,但当我想要删除任务时却遇到了问题。你有什么解决方案吗? - Yogendra Singh
2个回答

3

首先尝试打破关联:

Task record = hibernateTemplate.load(Task.class, id);
Project project = hibernateTemplate.load(Project.class, projectId);
project.getTasks().remove(record);
hibernateTemplate.update(project);
hibernateTemplate.delete(record);

如果您没有项目ID可用,您可能希望在任务内创建一个反向的ManyToOne关系。

我尝试了你的解决方案,但我的控制台显示了错误:ERROR org.hibernate.LazyInitializationException - could not initialize proxy - no Session。那么问题出在哪里呢?你知道为什么会出现这个错误吗? - Yogendra Singh
这很奇怪,因为任务集合已经被急加载。哪个语句引发了它?这可能是与 Hibernate 模板相关的问题,据我所记,每个调用都有自己的会话。你能切换到普通的 Hibernate 会话吗(例如没有 Hibernate 模板)? - Kevin Schmidt
感谢您的回复。在将 Hibernate 模板更改为普通的 Hibernate 会话后,一切都开始完美地运作。 - Yogendra Singh

0
也许你应该更改项目中的任务集,然后尝试删除任务...
我认为你也可以在setTasks上使用cascade.type All...
你必须从任务集中删除你想要删除的任务...并更新实体。

我在我的项目Pojo中实际上已经实现了**@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)**。我只想删除我的任务以及它在project_task表中的所有关联外键,你有什么解决方案吗? - Yogendra Singh
请告诉我们您遇到了什么错误...如果没有任何错误,请检查您的数据库而不是代码 :) Hibernate有一些缓存问题.. - Alex
Hibernate没有给我错误名称**Cannot delete or update a parent row: a foreign key constraint fails (primavera.project_task, CONSTRAINT FK3800AAEBACB7568D FOREIGN KEY (taskid) REFERENCES task (taskid))**,因为连接表project_task中有taskid,删除过程无法删除任务。那么我该如何删除包含taskid的连接表project_task呢? - Yogendra Singh
如果你只是像这样设置: tasks.setTasks(---没有那个任务的设置---); 会发生什么?难道不起作用吗? - Alex
Alex,你误解了我的意思。我想从创建的关联表project_task中删除Task对象。如果我根据ID删除任务,就会出现上述错误。那么有没有更好的方法可以成功删除任务,并且我的关联表project_task的taskid也被删除? - Yogendra Singh
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接