可以使用Spring Data REST api以某种方式(通过投影或其他方式)填充实体类中的瞬态字段 - 在JSON响应中获取该值吗?我需要填充例如info
字段,其值来自第二个数据源(我有这个数据源的Spring repo bean,需要注入类似“拦截器”的东西并填充该字段)。
@Entity
public class User {
@Id
private Long id;
@Transient
private String info;
// getters & setters
}
public interface UserRepository extends JpaRepository<User, Long> {
}
答案 0 :(得分:1)
我使用PostLoadEventListener找到了解决方案,但它适用于Hibernate,不完全是我想要的,但有效。我认为它应该是更普遍的Spring-ly解决方案。
@Component
public class UserInterceptor implements PostLoadEventListener {
@Autowired
private SecondRepository repo;
@Autowired
@Qualifier("prmiaryEntityManagerFactory")
private EntityManagerFactory entityManagerFactory;
@PostConstruct
private void init() {
HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) this.entityManagerFactory;
SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
registry.appendListeners(EventType.POST_LOAD, this);
}
@Override
public void onPostLoad(PostLoadEvent event) {
final Object entity = event.getEntity();
if(entity != null && entity instanceof User) {
User user = (User) entity;
// populate using another repo bean
Info s = repo.findOne(user.getInfoId());
user.setInfo(s.getName());
}
}
}