Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate @Transient field within Spring Data Jpa Repository

Is possible to populate transient field in entity class with Spring Data REST api somehow (by projection or something) - to get that value in JSON response ? I need to populate for example info field with value got from second datasource (i had Spring repo bean for this datasource and need inject it in something like "interceptor" and fill that field).

@Entity
public class User {
   @Id
   private Long id;

   @Transient
   private String info;

   // getters & setters
}

public interface UserRepository extends JpaRepository<User, Long> {
}
like image 229
marioosh Avatar asked Nov 21 '25 16:11

marioosh


1 Answers

I found solution using PostLoadEventListener, but it is for Hibernate, not exactly what i was looking for, but works. I think it should be more general Spring-ly solution.

@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());
        }
    }

}
like image 54
marioosh Avatar answered Nov 24 '25 07:11

marioosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!