MyBatis環境配置

  • 在src下創建一個包,如cn.elinzhou.config(我的習慣,把配置文件放在這裏)建立一個Configuration.xml文件,該文件爲MyBatis核心配置文件。
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2009-2012 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
  <!--<settings>-->
    <!--<setting name="useGeneratedKeys" value="false"/>-->
    <!--<setting name="useColumnLabel" value="true"/>-->
  <!--</settings>-->

  <!--<typeAliases>-->
    <!--<typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>-->
  <!--</typeAliases>-->

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
          <!--鏈接的驅動-->
        <property name="driver" value="com.mysql.jdbc.Driver"/>
          <!--鏈接的數據庫-->
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/message?characterEncoding=UTF-8"/>
          <!--用戶名-->
        <property name="username" value="root"/>
          <!--密碼-->
        <property name="password" value=""/>
      </dataSource>
    </environment>
  </environments>

  <mappers>
    <mapper resource="me/elin/config/sql/Message.xml"/>
    <mapper resource="me/elin/config/sql/Command.xml"/>
    <mapper resource="me/elin/config/sql/CommandContent.xml"/>
  </mappers>

</configuration>
  • 要經過MyBatis 操做數據庫,實際是經過操做Mybat封裝的一個SqlSession對象。
// 經過配置文件獲取數據庫鏈接信息
Reader reader = Resources.getResourceAsReader("cn/elinzhou/config/Configuration.xml");
// 經過配置信息構建一個SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 經過sqlSessionFactory打開一個數據庫會話
SqlSession sqlSession = sqlSessionFactory.openSession();

其中」cn/elinzhou/config/Configuration.xml」爲Configuration.xml相對於src文件的路徑,其實只要把包名的.改成/就好mysql

相關文章
相關標籤/搜索