Null embedded ID transient field for multiple returned entities

I suspect this is not a Hibernate Search issue, but an issue with your code or ORM. Try executing a Hibernate ORM query on this entity, with multiple results; I suspect you will have the same problem.

To be honest, what surprises me most is that this works at all, even partially. I would expect the field to always be null. But it seems in some cases the ID object you created is set on the loaded entity, which leads to your single working case. I suppose in most other cases, a new ID object is built.

The proper way to initialize this transient field, I think, would be to declare a @PostLoad method on the entity, which would call some initialize() method on the ID. But that probably won’t work on proxies.

I guess updating this transient field anytime one of the fields it’s based on is modified would be the safest course of action. Something like that:

@Access(AccessType.PROPERTY)
public class MyId {
  private Integer myField1;
  private Integer myField2;
  @Transient
  private transient Integer myTransientField;

  protected MyId() {
    // For Hibernate
  }

  public MyId(int myField1, int myField2) {
    this.myField1 = myField1;
    this.myField2 = myField2;
    updateTransientField();
  }

  protected int setMyField1(int value) {
    this.myField1 = value;
    updateTransientField();
  }

  protected int setMyField2(int value) {
    this.myField2 = value;
    updateTransientField();
  }

  private void updateTransientField() {
    if ( myField1 != null && myField2 != null ) {
      this.myTransientField = myField1 + myField2;
    }
  }
}