Pergunta

i have a Problem while testing my DAOObject. I have two Entitys which are linked by a @oneToOne relation. The Classes are:

@Entity
@Table
public class Device extends HyEntity {

    @OneToOne(mappedBy = "device")
    private EndUser endUser;
    //getters+setters
}

and

@Entity
@Table
public class EndUser extends HyEntity {

    private String firstname;
    private String lastname;
    @OneToOne
    private Device device;
    //getters+setters
}

In the DAO i do the Following:

    Device d1 = new Device();

    EndUser e1 = new EndUser();
    e1.setFirstname("Hans");
    e1.setLastname("Muster");
    e1.setDevice(d1);

    repo.saveEntity(d1);
    repo.saveEntity(e1);
    sf.getCurrentSession().flush();
    repo.updateEntity(d1);
    sf.getCurrentSession().flush();

    Assert.notNull(repo.getEndUserById(e1.getId()));
    Assert.notNull(repo.getEndUserById(e1.getId()).getDevice());
    Assert.notNull(repo.getDeviceById(d1.getId()));

    sf.getCurrentSession().flush();
    d1 = repo.getDeviceById(d1.getId());
    Hibernate.initialize(d1); 
    Hibernate.initialize(d1.getEndUser());
    Assert.notNull(repo.getDeviceById(d1.getId()).getEndUser()); //FAILS endUser of Device is always NULL

As you can see, neither session.flush() nor Hibernate.Initalize works. The endUser is not assigend to the device. If I remove the @Transactional, ... everything works as it should. Is there a way to get this to work? Otherwise i'll always have to delete the created entities in the Database manually after the test, which is pretty anoying.

Hoping for an Answer.

Thanks in Advance.

Foi útil?

Solução

You need to add a clear() after the last flush. If you miss that, than hibernate will return exactly the SAME instance from its internal cache, where the releationship is not updated.

Anyway in my personal opinion it is bad practice not to set the relation ship on both sides by hand. -- Because if you do not set it on both sides, you always must take care that the entity is reloaded from the database. And if you do not reload the entity from the database than ... (see your test).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top