3

I would like to enrich entity with additional data on load from DB inside @PostLoad.

How can I access to Spring managed beans inside @PostLoad method?

I use ugly solution with static accessor:

@Service
public class StaticApplicationContext implements ApplicationContextAware {
    private static ApplicationContext ctx = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }
}

@Entity
public class Car {
    @Id
    private Long id;
    ...
    @Transient
    private List<XType> details;

    @PostLoad
    private void onLoad() {
         XTypeRepository repo = StaticApplicationContext.getCtx()
                .getBean(XTypeRepository.class) ;
         this.details = repo.findByCarId(this.id);
    }
}

Corresponding idea for static access described in Accessing spring beans in static method

Is there more idiomatic solution / framework sugar?

Community
  • 1
  • 1
gavenkoa
  • 45,285
  • 19
  • 251
  • 303

1 Answers1

2
@OneToMany
@JoinFormula(value = "SELECT * FROM xTypeTable xt WHERE xt.carId = id") 
private List<XType> pastArticles;

Can't you just use JoinFormula and load the data with standard tools? Just write SQL which retrieves data for the XType. In the example above replace id with column name of id property (if it's different)

StanislavL
  • 56,971
  • 9
  • 68
  • 98