0


I'm integrating MyBatis inside my SpringBoot application. The application connects to a MySql database to fetch data. Right now I have the following classes.

MyBatisUtils.java

[...]
    @Component
    public class MyBatisUtils {

        private static SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(getConfiguration());

        public static SqlSessionFactory getSqlSessionFactory(){
            return sqlSessionFactory;
        }

        private static Configuration getConfiguration(){
            Configuration configuration = new Configuration();

            DataSource dataSource = null; //wrong!!!
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("development", transactionFactory, dataSource);

            configuration.addMapper(BaseQuery.class);
            return configuration;
        }
    }

Search.java

[...]
    public List dynamicSearch(){

            SqlSession session = MyBatisUtils.getSqlSessionFactory().openSession();
            BaseQuery mapper = session.getMapper(BaseQuery.class);

            List<HashMap<String, Object>> result = mapper.select(/*query parameters*/);

            return result;
        }

I do not know how to set my DataSource object inside the MyBatisUtils class. Should it have some connection parameters?
Thanks for the help.

esseara
  • 834
  • 5
  • 27
  • 47

2 Answers2

0

Define the DataSource as a Spring bean, like in this other question: How to Define a MySql datasource bean via XML in Spring Then inject the datasource in MyBatisUtils class.

You can also define SqlSessionFactory as a Spring bean, and directly inject it. Useful reference: http://www.mybatis.org/spring/getting-started.html

0

If you are using spring-boot already you can use mybatis-spring-boot-starter and auto-configure mybatis for free. The only thing you should worry about is the datasource. For that, properties should be set in application.properties

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass

You can find more info here

Eddú Meléndez
  • 6,107
  • 1
  • 26
  • 35