javahibernatequarkuscdi

Bean injection into Hibernate BeforeExecutionGenerator


I'm using Hibernate's BeforeExecutionGenerator together with IdGeneratorType annotation to generate custom ids for my entities.

How could I inject some beans (or config properties) into my implementation of generator?

Here is the code:

@Entity
@Table(name = "my_entity")
public class MyEntity {

    @Id
    @MyIdGeneratorValue
    @Column(name = "id")
    private Long id;

    //other fields
}

@IdGeneratorType(MyIdGenerator.class)
@Retention(RUNTIME)
@Target({METHOD, FIELD})
public @interface MyIdGeneratorValue {
}


public class MyIdGenerator implements BeforeExecutionGenerator {

    //doesn't work
    @Inject
    OtherService service;

    @Override
    public Object generate(SharedSessionContractImplementor session, Object owner, Object currentValue,
                           EventType eventType) {
        return service.nextId();
    }

    @Override
    public EnumSet<EventType> getEventTypes() {
        return INSERT_ONLY;
    }

}

I've already tried simply adding @Inject on service field, also tried making generator class @ApplicationScoped, but no result. I'm using Quarkus as CDI implementation.


Solution

  • You need to retrieve OtherService in a programmatic way using CDI.current().select(OtherService.class).get()