MyBatisのデータソースを設定する方法は?

MyBatisのデータソースを設定するには、まずMyBatisの設定ファイルでデータソースの情報を指定する必要があります。以下は設定ファイルの例です:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/mybatis/mapper.xml"/>
    </mappers>
</configuration>

構成ファイルで、要素を使用して、データソースのタイプをPOOLEDに指定し、データベースのドライバー、接続URL、ユーザー名、パスワードなどの情報を指定しました。これらの設定情報は必要に応じて変更することができます。

その他にも、この設定ファイルをMyBatisの設定クラスで読み込んで、SqlSessionFactoryオブジェクトを作成する必要があります。

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

この例では、「mybatis-config.xml」という設定ファイルがロードされ、SqlSessionFactoryBuilderを使用してSqlSessionFactoryオブジェクトが作成されました。次に、このSqlSessionFactoryオブジェクトを使用してSqlSessionを取得し、データベース操作を実行することができます。

コメントを残す 0

Your email address will not be published. Required fields are marked *