Search code examples
javahibernatejpaormhibernate-mapping

how to use FetchType.EAGER


I'm not able to load, from DB, an object with its relative mapped objects. Probably my "map system" is wrong.

When saving an object (and its relative mapped objects) in the DB everything is ok, so the objects seem to be correctly mapped.

Utente is my "master" object

   public class Utente implements Serializable{
        .......    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id_utente", unique = true, nullable = false)
        private Integer idUtente;    
        .......

I haven another object called Autenticazione, where I link Autenticazione to Utente

public class Autenticazione implements Serializable{    
    ....
    @OneToOne(targetEntity=Utente.class)
    @JoinColumn(name="utente", referencedColumnName="id_utente")    
    private Utente utente;
    ...

When I get from the db a Utente object, I want to get also its Autenticazione object. I tried some code (not posted here to avoid confusion), but i didn't find a solution.


Solution

  • You need to add an association from Utente to Autenticazione too:

    public class Utente implements Serializable{
        .......    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id_utente", unique = true, nullable = false)
        private Integer idUtente;    
        .......
    
        @OneToOne(mappedBy = "utente")
        private Autenticazione autenticazione;
    

    Make sure you set both sides of the associations with a helper method like one you should add to Utente:

        public void addAutenticazione(Autenticazione autenticazione) {
            autenticazione.setUtente(this);
            this.autenticazione = autenticazione;
        }