如何使用Hibernate在Child列上设置上一个Parent id

时间:2015-06-03 14:08:00

标签: java sql database hibernate orm

我有父母和子女实体:

@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;**

.....

}

问题是我每次创建父级时都需要在子级中更新lastParentId。 换句话说,在创建父项之前,子项存在于数据库中,子项被分配了#39;给他。并且在每个父插入之后,应该使用新创建的父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

我尝试通过手动最大选择来分配此列,但是可能在select max()和save其他进程之间插入新的父级,因此在子级保存之前,最后一个id将变得过时。我如何在休眠中执行此操作并确保此lastId真的是最后一次?

2 个答案:

答案 0 :(得分:2)

最好的方法是在Child表中使用BEFORE UPDATE TRIGGER,该表会检查旧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;

答案 1 :(得分:0)

public Long lastParentId;更改为@ManyToOne public Parent latestParent;,并在创建新Child时更新Parent