How to iterate or traverse an Object of the Object class that contains objects of different class inside it?

0

I have this query in hql:

String lHql = " from  Grupo g"
                + " join g.Persona p " 
                + " join g.Animal a "
                + " where g.tipo= "A"";
        Query lQuery = pSession.createQuery(lHql);

        Object lResult  = (Object) lQuery.uniqueResult();

The problem is that it returns 3 different objects (Group, Person and Animal). If you only return Group, assign the result to a Group object and you're done. It does not let me assign the result to an Arraylist, I can only assign it to the generic class Object. By debugging it is clear that the variable LResult has 3 objects inside, each with its attributes. The problem is that I do not know how to go find those objects and pick them up, it does not leave me because lResult is not an array. Thanks

    
asked by Xavier 23.12.2018 в 18:50
source

2 answers

1

If you are using hql (Hibernate or similar), it is common to bring a main object of the BD and other related objects, for which you should determine what is the main object of your query, let's say it is Group. Your class Group should have all its attributes and also an attribute "Person" and an attribute "Animal", this is the grace of the hql. bring all related objects in one shot.

public class Grupo(){
  private int grupoId;
  ...
  @OneToMany
  private Persona persona;
  @OneToMany
  private Animal animal;
  ...
}

and in this way you only get your Group object and then you can do something like

Grupo grupo = //obtener grupo desde BD
grupo.getPersona();

And there you should be able to see all the attributes of person Greetings

    
answered by 24.12.2018 в 18:38
0

One way is to save each element you retrieve in an array as an object and then select and store it in a class or variable of interest as you classify it.

ejm

public void resultados(){
    List<Object> valoresMixtos = new ArrayList<>();
    valoresMixtos.add(new Empleado(0, "Andres", "Ventas", 32.5));
    valoresMixtos.add(new Entidad(2, "1258475", "Juan", "Nov"));
    valoresMixtos.add(new Empleado(0, "Ramon", "Ventas", 32.5));

    valoresMixtos.forEach(elemento ->{
        if(elemento instanceof Empleado) System.out.println("Tipo Empleado");
        if(elemento instanceof Entidad) System.out.println("Tipo Entidad");
    });

}
    
answered by 24.12.2018 в 02:13