2
I have a relatively simple problem to solve, but I’m not succeeding because of a logical deficiency. My problem is this::
I have a hierarchy of leaders and leaders. For example:
Lider 1
Lider 1.1
Lider 1.1.1
Lider 1.1.2
Lider 1.1.3
Lider 1.1.3.1
Lider 1.2
Lider 1.2.1
Lider 1.3
And so it goes. As many levels are needed. In the database, this is already mapped. That is, I can know who is the leader of whom using the following example query:
select * from colaboradores where lider_id = ?;
However, I’m unable to mount an efficient Java recursion to return all the leaders below. For example, if I pass leader ID 1.1 to my method, it should return to me a list like this:
Lider 1.1
Lider 1.1.1
Lider 1.1.2
Lider 1.1.3
Lider 1.1.3.1
Somebody got a light for me there?
UPDATING: I tried mapping JPA itself. Just one note: The relationship between leaders and led is not done via class ID, but another field that is not foreign key. This other field is the license plate. Look:
@ManyToOne(targetEntity = Colaborador.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "matricula_lider", referencedColumnName = "matricula", insertable = false, updatable = false)
private Colaborador lider;
@OneToMany(mappedBy="lider", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
private List<Colaborador> liderados;
Well, if I just use the mapping:
@ManyToOne(targetEntity = Colaborador.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "matricula_lider", referencedColumnName = "matricula", insertable = false, updatable = false)
private Colaboradorlider;
It works cool and I can get the person’s leader. If I use both mappings (bi-directional), error while trying to recover. Actually no error, it seems that enters in infinite loop until giving timeout of the transaction.
javax.persistence.PersistenceException: org.hibernate.HibernateException: Transaction was rolled back in a different thread!
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
...
My mapping is wrong?
Highly related reading suggestion: http://answall.com/questions/2425/comormodelr-uma-structura-datastructures-em-%C3%A1rvore-using-a-related-database
– utluiz
Implementation suggestions will depend on your logical model. Can a group have more than one leader? Can a leader be a collaborator of another group? A leader can be a leader of several groups?
– OnoSendai