开发者

Delete item from collection in Hibernate without loading entities

I have three tables:

user(id, name), 
group(id, name), 
xref_user_group(user_id, group_id)

I have Two java classes:

User {
    int id;
    String name;
}

Group {
    int id;
    String name;
    Set<User> users;
}

Can I delete user from group (and not deleting user) without loading group object in memory. I need some kind of HQL query. Smth like(my imagination):

delet开发者_如何学Pythone user from Group where user.name = :username

I can't add any database or Hibernate cascades.

I need it to be transactional.

If it is not possible to do it via HQL and without loading objects in memory what is the best solution?


your hql should work as your requirement, as well as in jpa environment :) Session.createQuery("....").executeUpdate()


Er first you ask for HQL and then say you can't run HQL. Which is it.

If you can use HQL your basic HQL delete will work. It never cascades (which can be a problem), never loads, etc. See "bulk update operations" in the hibernate doc for more info.

If you can't use HQL then use query.createSQLQuery or whatever it is to do the native SQL.

Finally a 3rd option is to use a StatelessSession - that's discussed in the hibernate doc as well.

Here is the relevant link. Read it, understand it, love it :)


You cannot write that query. If this is a real requirement, you'll probably need to either promote your join table to be a full Entity so that you can remove it directly, or write the query in native SQL.

Another alternative may be to map your users as a MAP and use extra-lazy loading to avoid loading excess users.


Yes, this is possible with HQL, and no, it will not require loading groups into memory.

If you want to delete one user from one group, the following HQL should be pretty close:

delete g.users from Group g where g.users.name = :username and g.id = :groupId

Alternately, if you're trying to delete a user from all groups, just drop the second part of the where:

delete g.users from Group g where g.users.name = :username
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜