【问题标题】:Spring + MyBatis - setting Data SourceSpring + MyBatis - 设置数据源
【发布时间】:2018-01-25 17:23:14
【问题描述】:


我正在将MyBatis 集成到我的SpringBoot 应用程序中。应用程序连接到 MySql 数据库以获取数据。现在我有以下课程。

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;
        }

我不知道如何在MyBatisUtils 类中设置我的DataSource 对象。它应该有一些连接参数吗?
感谢您的帮助。

【问题讨论】:

    标签: mysql spring-boot mybatis


    【解决方案1】:

    如果你已经在使用spring-boot,你可以使用mybatis-spring-boot-starter并免费自动配置mybatis。您唯一应该担心的是数据源。为此,属性应设置在application.properties

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

    您可以找到更多信息here

    【讨论】:

      【解决方案2】:

      将 DataSource 定义为 Spring bean,就像在另一个问题中一样: How to Define a MySql datasource bean via XML in Spring 然后在 MyBatisUtils 类中注入数据源。

      你也可以将SqlSessionFactory定义为一个Spring bean,直接注入。有用的参考:http://www.mybatis.org/spring/getting-started.html

      【讨论】:

        猜你喜欢
        • 2011-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 2013-05-04
        • 1970-01-01
        • 2016-12-20
        相关资源
        最近更新 更多