2017-04-10 2 views
1

Ich möchte Entity mit zusätzlichen Daten beim Laden von DB innerhalb @PostLoad anreichern.Zugriff auf Spring-Beans in Hibernate verwalteter Entity-Methode, die mit @PostLoad markiert ist

Wie kann ich auf Spring verwaltete Bohnen innerhalb @PostLoad Methode zugreifen?

Ich benutze hässliche Lösung mit statischem 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); 
    } 
} 

Entsprechende Idee für static beschrieben Zugang in Accessing spring beans in static method

Gibt es mehr idiomatische Lösung/framework Zucker?

Antwort

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

Können Sie JoinFormula nicht einfach verwenden und die Daten mit Standardwerkzeugen laden? Schreiben Sie einfach SQL, das Daten für den XType abruft. Im obigen Beispiel ersetzen Sie die ID durch den Spaltennamen der ID-Eigenschaft (wenn es anders ist)

Verwandte Themen