我目前有几个实体作为树,需要将它们保存到数据库。
因此,为了不重复代码,我构建了此类:
@MappedSuperclass
public abstract class TreeStructure<T extends TreeStructure>
{
@ManyToOne(cascade = CascadeType.PERSIST)
private T parent;
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
protected Set<T> children = new HashSet<>();
/**
* Function that is used before deleting this entity. It joins this.children to this.parent and viceversa.
*/
@Transactional
@PreRemove
public void preDelete()
{
unregisterInParentsChildren();
while (!children.isEmpty())
{
children.iterator().next().setParent(parent);
}
}
public abstract long getId();
protected void setParent(T pParent)
{
unregisterInParentsChildren();
parent = pParent;
registerInParentsChildren();
}
/**
* Register this TreeStructure in the child list of its parent if it's not null.
*/
private void registerInParentsChildren()
{
getParent().ifPresent((pParent) -> pParent.children.add(this));
}
/**
* Unregister this TreeStructure in the child list of its parent if it's not null.
*/
private void unregisterInParentsChildren()
{
getParent().ifPresent((pParent) -> pParent.children.remove(this));
}
/**
* Move this TreeStructure to an new parent TreeStructure.
*
* @param pNewParent the new parent
*/
public void move(final T pNewParent)
{
if (pNewParent == null)
{
throw new IllegalArgumentException("New Parent required");
}
if (!isProperMoveTarget(pNewParent) /* detect circles... */)
{
throw new IllegalArgumentException(String.format("Unable to move Object %1$s to new Object Parent %2$s", getId(), pNewParent.getId()));
}
setParent(pNewParent);
}
所以,最后要说的是:有没有以更好/更干净的方式实现这一点?这个警告有意义,还是只是Intellij不够聪明?
呼如林
慕侠2389804
守着一只汪
随时随地看视频慕课网APP
相关分类