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

相关文章
相关标签/搜索