MyBatis+Spring - Retrieve VOs as "beans"

37 views
Skip to first unread message

Vladimir Alarcon

unread,
May 24, 2019, 10:11:18 AM5/24/19
to mybati...@googlegroups.com
My sqlSession.selectList() method is retrieving a list of VOs.

Do you guys know if it's possible for these VOs to be instantiated by
Spring? I would like them to be able to control Spring SQL
transactions.

So far my VOs look like:

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class AccountVO {

@Autowired
private InvoiceController invoiceController;

}

When I run the SELECT using MyBatis+Spring, the returned AccountVO
"autowired properties" are not populated as I wished, but always null.

Any insight would be greatly appreciated.

Thanks in advance.
Vlad

Iwao AVE!

unread,
May 28, 2019, 9:52:10 AM5/28/19
to mybatis-user

Hi Vlad,

I would like them to be able to control Spring SQL transactions.

I am not sure what that means, but it is possible to let MyBatis use Spring managed beans.

You need to create a custom ObjectFactory that looks up ApplicationContext.
The create method would look as follows.

public <T> T create(Class<T> type) {
  try {
    return applicationContext.getBean(type);
  } catch (NoSuchBeanDefinitionException e) {
    return delegate.create(type);
  }
}

delegate is an instance of DefaultObjectFactory.

Set this ObjectFactory to your SqlSessionFactoryBean.

@Bean
public SqlSessionFactoryBean sqlSessionFactory() {
  SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  sessionFactory.setObjectFactory(new SpringBeanObjectFactory(applicationContext));
  ...

Here is an executable demo:
https://github.com/harawata/mybatis-issues/tree/master/ml-20190524T021118

Regards,
Iwao


--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mybatis-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mybatis-user/CAP3Y0VaHJDctWxFo5wJRtKO0QDsAAaRdEpNHuupreu5bf-QhqA%40mail.gmail.com.

Kazuki Shimizu

unread,
May 28, 2019, 1:37:34 PM5/28/19
to mybatis-user
Be careful a performance degradation when use the spring managed prototype bean.
To unsubscribe from this group and stop receiving emails from it, send an email to mybati...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages