RBP
RBP

Reputation: 485

How to delete records in hibernate one to many relationship

I have two tables, one is QuickLinks and another is OrgUnit. OrgUnit table is Parent and QuickLinks table is child. I have added relationship in QuickLinks table as Many to One.

@Entity
@Table(name ="TBL_STD_QUICK_LINKS")
public class QuickLinks {
    @Id
    @GeneratedValue
    @Column(name = "FLD_QUICK_LINK_ID")
    private Long quickLinkId;

    @Column(name = "FLD_DISPLAY_NAME")
    private String displayName;

    @ManyToOne
    private OrgUnit orgUnit; 
}



@Entity
@Table(name = "TBL_STD_ORG_UNIT")
public class OrgUnit implements Serializable  {
@Id
@GeneratedValue
@Column(name = "FLD_ORGUNIT_ID")
private Long orgUnitId;

@Column(name = "FLD_OUNAME")
private String ouName;

@Column(name = "FLD_OUPARENT_ID")
private Long ouParentId;

@Column(name = "FLD_OUPATH")
private String ouPath;

}

I want to delete records QuickLinks table , who's FLD_OUPATH from OrgUnit starts with '/abc/xyz'.

Query executeQuery = getSession().createQuery("delete from QuickLinks as links where links.orgUnit.ouPath like :OrgName");
 executeQuery.setParameter("OrgName", ouPath+"%");
 executeQuery.executeUpdate();

but I am getting exceptions while executing this query. So can anyone tell me what is wrong in it.?

Upvotes: 1

Views: 1366

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

Quote from the documentation:

No forms of join syntax, either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins.

links.orgUnit

is an implicit inner join, and is thus not acceptable.

You could use a native (SQL) query. Or, as the documentation hints, you could use a subquery:

delete from QuickLinks as link where link.id in 
    (select link2.id from QuickLinks link2 
     where link2.orgUnit.ouPath like :orgName)

Side note: QuickLinks should be named QuickLink.

Upvotes: 1

Related Questions