Final solution:
@Override
public Webpage getTopParentWebpage(final Webpage childrenNode) {
Validate.notNull(childrenNode);
StringBuilder sql = new StringBuilder();
sql.append("with recursive tmp_webpage(id, parent) as ( ")
.append(" values(-1::BIGINT, :childrenNodeId::BIGINT) ")
.append(" union all ")
.append(" select w.id, w.parent_id ")
.append(" from tmp_webpage as tw, webpage as w ")
.append(" where w.id = parent ")
.append(" ) ")
.append(" select * from webpage w where id = ( select t.id from tmp_webpage as t where t.parent is NULL ) ");
Query query = sessionFactory.getCurrentSession().createSQLQuery(sql.toString())
.addEntity(Webpage.class)
.setMaxResults(1)
.setLong("childrenNodeId", childrenNode.getId());
return (Webpage)query.uniqueResult();
}
SQL Query:
with recursive tmp_webpage(id, parent) as (
values(-1::BIGINT, :childrenNodeId::BIGINT)
union all
select w.id, w.parent_id from tmp_webpage as tw, webpage as w
where w.id = parent
)
select * from webpage where id = ( select t.id from tmp_webpage as t where t.parent is NULL ) ;
NOTE: :childrenNodeId must bind/replace of you children node ID. Value -1, represents initial value.
I hope thats help