I have parent and child entities:
我有父实体和子实体:
@Entity
public class Parent{
@Id
private Long id;
@ManyToOne
private Child child;
.....
}
@Entity
public class Child{
@Id
private Long id;
public List<Parent> all parents;
**public Long lastParentId;**
.....
}
The issue is I need to update lastParentId in child every time I create parent. In other words, child exists in DB before parent is being created, child is 'assigned' to him. And after every parent insert child's field should be updated with newly created parent id, and this id should be last for this child. In other words:
问题是每次我创建父节点时,我都需要更新lastParentId。换句话说,在创建父元素之前,子元素存在于DB中,子元素被“分配”给父元素。在每个父插入子字段之后,应该使用新创建的父id更新该子字段,并且该id应该为该子字段保留。换句话说:
Long childId=12323L;//lastParentId in child with id=12323L is 1234
Parent p=new Parent();
...
p.setChildId(childId);
getDao().insert(p);//lastParentId in child=1235, 1235- newly created parent id
I tried to assign this column by manual max select, but it possible that between select max() and save other processes insert new parent, so last id becomes obsolete before child save. How can I do this in hibernate and ensure that this lastId is really last?
我尝试通过手动max select来分配这个列,但是在选择max()和保存其他进程之间插入新父进程的过程中,最后一个id在孩子保存之前就已经过时了。我如何在休眠状态下做到这一点,并确保这个lastId真的是最后的?
2 个解决方案
#1
2
The best way is to use a BEFORE UPDATE TRIGGER in the Child
table, which check the old parent_id
column and saves it to last_parent_id
:
最好的方法是在子表中使用BEFORE UPDATE触发器,该触发器检查旧的parent_id列并将其保存到last_parent_id:
CREATE TRIGGER last_parent_id_check BEFORE UPDATE ON child
FOR EACH ROW
BEGIN
IF NEW.parent_id <> OLD.parent_id THEN
SET NEW.last_parent_id = OLD.parent_id;
END IF;
END;
#2
0
change public Long lastParentId;
to @ManyToOne public Parent latestParent;
and update the Child
when new Parent
is created.
改变公众长lastParentId;@ManyToOne public Parent last Parent;并在创建新父元素时更新子元素。
#1
2
The best way is to use a BEFORE UPDATE TRIGGER in the Child
table, which check the old parent_id
column and saves it to last_parent_id
:
最好的方法是在子表中使用BEFORE UPDATE触发器,该触发器检查旧的parent_id列并将其保存到last_parent_id:
CREATE TRIGGER last_parent_id_check BEFORE UPDATE ON child
FOR EACH ROW
BEGIN
IF NEW.parent_id <> OLD.parent_id THEN
SET NEW.last_parent_id = OLD.parent_id;
END IF;
END;
#2
0
change public Long lastParentId;
to @ManyToOne public Parent latestParent;
and update the Child
when new Parent
is created.
改变公众长lastParentId;@ManyToOne public Parent last Parent;并在创建新父元素时更新子元素。