简体   繁体   English

休眠。 删除未使用的条目

[英]Hibernate. Delete unused entry

I have a table looks which like this: 我有一个看起来像这样的表:

ID  USER_NAME ROOM_ID
 1  user1   13
 2  user2   11  
 3  user3   null
 4  user4   4   
 5  user5   2   

And Room table 和房间表

ID  ROOM_NAME SQUARE
13  room1   17
 4  room2   42  
 2  room3   26
11  room4   37  
 5  room5   28  

In my application i can change User's ROOM_ID, for example, for Null. 在我的应用程序中,例如,可以将用户的ROOM_ID更改为Null。 And after this, i'll have a one "Unused" room (There's no user in this room). 之后,我将拥有一个“未使用”的房间(此房间中没有用户)。

So, the question is: How can i delete this room automaticly using Hibernate? 因此,问题是: 如何使用Hibernate自动删除此会议室?

Thanks! 谢谢!

you can use a trigger for that: 您可以为此使用触发器:

CREATE OR REPLACE FUNCTION delete_room()
  RETURNS trigger AS
$BODY$
BEGIN
 DELETE FROM ROOMS WHERE (OLD.ROOM_ID = ID)
 RETURN NEW;
END;
$BODY$


CREATE TRIGGER delete_room_changed
  BEFORE UPDATE
  ON USERS
  FOR EACH ROW
  EXECUTE PROCEDURE delete_room()

that way when you update any user the assigned room is deleted 这样,当您更新任何用户时,分配的房间将被删除

Try this code - see the comments for details: 尝试使用此代码-有关详细信息,请参见注释:

Session session = null;
if(session == null) {
    initTransaction();
}

Room room = (Room) session.createCriteria(UserRoomTable.class); // First table Pojo class name
room.add(Restrictions.isNull("roomId"));
session.delete(room); // This deletes the unused entry

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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