2017-04-10 53 views
1

我想用@PostLoad中的數據庫加載其他數據來豐富實體。用@PostLoad標記的在Hibernate管理實體方法中訪問Spring beans

如何訪問@PostLoad方法中的Spring managed beans?

我用靜態訪問醜陋的解決方案:

@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); 
    } 
} 
Accessing spring beans in static method

描述static訪問

通訊的想法是有更地道的解決方案/框架糖嗎?

回答

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

難道你不能只使用JoinFormula並使用標準工具加載數據嗎?只需編寫用於檢索XType數據的SQL。在上面的例子中,用id屬性的列名替換id(如果它不同)