MyBatis 配置文件

MyBatis 的核心配置文件中,包含了很多影响MyBatis 行为的重要信息。这些信息通常在一个项目中只会在一个配置文件中编写,并且编写后也不会轻易改动。

MyBatis 配置文件中的主要元素如下:


  注意<configuration>的字元素 必须按照上图中由上至下的顺序进行配置,否则MyBatis 在解析XML配置文件的时候会报错误。

 一、 <properties>元素

 1.在src目录下添加一个db.properties的配置文件

jdbc.driver    = com.mysql.jdbc.Driver
jdbc.url       = jdbc:mysql://localhost:3306/mybatis
jdbc.username  = root
jdbc.password  = kangxg198811
 2. 在MyBatis配置文件中 增加配置<properties .../>属性

<configuration>
  <properties resource = "db.properties"/>
3.修改配置文件中数据库连接的信息

      <!-- 数据库连接池-->
      <dataSource type="POOLED">
         <!-- 数据库驱动 -->
         <property name = "driver" value = "${jdbc.driver}" />
         <!-- 连接数据库URL-->
         <property name = "url" value = "${jdbc.url}" />
         <!-- 连接数据库的用户名-->
         <property name = "username" value = "${jdbc.username}" />
         <!-- 连接数据库的密码-->
         <property name = "password" value = "${jdbc.password}" />
      </dataSource>

二、 <sql>元素

    在一个映射文件中国呢,通常需要定义多条SQL语句,这些SQL语句的组成可能有一部分是相同的(如select 语句中都是查询id、username、jobs字段),如果每一个SQL语句都重写一遍相同的部分,势必增加代码量,导致映射文件臃肿,因此用<sql>元素可以解决这个问题。


  <!-- 定义表的前缀名  -->
  <sql id = "tablename">
     ${prefix}customer
  </sql>
  <!--  定义要查询的表 -->
  <sql id = "someinclude">
     from
     <include refid = "${include_target}"/>
  </sql>
  <!-- 定义要查询的列  -->
  <sql id = "customerColumns">
     id,username,jobs,phone
  </sql>
  
  <!-- 根据客户编号获取客户信息  -->
  <select id="findCustomerById" parameterType = "Integer" resultType="com.kangxg.po.Customer">
     select
     <include refid ="customerColumns"/>  
     <include refid ="someinclude">
          <property name = "prefix" value = "t_"/>
          <property name = "include_target" value = "tablename"/>
     </include>
     where id = #{id}
  </select>
   ${prefix} 会获取name 为 prefix的值"t_",获取后所组成的表名为"t_customer";而第二个代码片段中的"${include_target}" 会获取name为"include_target" 的值"tablename",由于tablename 为第一个SQL片段的id值,所以最后要查询的表为"t_customer";

所以SQL片段在程序运行时,都是由MyBatis组合成的SQL语句执行需要的操作。

执行程序后,控制台输出:

Tue Jan 30 23:27:32 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
DEBUG [main] - ==>  Preparing: select id,username,jobs,phone from t_customer where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
Customer [id =1,username =kangxf, jobs =java, phone =13712345678]

三、 <resultMap>元素

 <resultMap>元素 表示将结果进行映射。

1 在mybatis数据库中创建表t_user并插入3条测试数据

mysql -u root -p

show databases;

create database mybatis;

use mybatis;

create table t_user( id int(32) primary key auto_increment, t_name varchar(50), t_age INT);

insert into t_user (t_name,t_age) values('kangxg',29);
insert into t_user (t_name,t_age) values('kangxl',28);
insert into t_user (t_name,t_age) values('kangxy',27);
2.在com.kangxg.po包中 创建持久化类User

package com.kangxg.po;

public class User {
      private Integer id;
      private String  name;
      private Integer age;
      public Integer getId()
      {
         return this.id ;
      }
      public void setId(Integer id)
      {
          this.id = id;
      }
        
      public String getName()
      {
         return this.name ;
      }
      public void setName(String name)
      {
          this.name = name;
      }
      public Integer getAge()
      {
         return this.age ;
      }
      public void setJobs(Integer age)
      {
          this.age = age;
      }
      
      @Override
      public String toString()
      {
          return "Customer [id =" + id +"," +"name =" +name +", age =" +age +"]";
      }
}


3.在com.kangxg.mapper包下创建映射文件UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace 表示命名空间  -->
<mapper namespace="com.kangxg.mapper.UserMapper">

  <resultMap type ="com.kangxg.po.User" id = "resultMap">
        <id      property  = "id"   column = "id"/>
        <result  property  = "name" column = "t_name"/>
        <result  property  = "age"  column = "t_age"/>
  </resultMap>
  
  <!-- 根据客户编号获取客户信息  -->
  <select id="findAllUser" resultMap = "resultMap" >
     select * from t_user
     
  </select>

</mapper
 4.在mybatis-config.xml配置文件中引入 UserMapper.xml

  <mappers>
    <mapper resource="com/kangxg/mapper/CustomerMapper.xml"/>
    <mapper resource="com/kangxg/mapper/UserMapper.xml"/>
  </mappers>
5.在单元测试类中 增加测试方法

    @Test
    public void findAllUserTest()throws Exception
    {
    
        // 通过 SqlSessionFactory 创建  sqlSession
        SqlSession sqlSession =  MybatisUtils.getSession();
        List<User> list = sqlSession.selectList("com.kangxg.mapper.UserMapper.findAllUser");
        
        for(User user:list)
        {
            System.out.println(user.toString());
        }
        
        sqlSession.close();
    }
6 debud运行程序

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值