Mybatis的配置文件以及mapper文件

在mybatis的配置文件中,所有的配置均是在 <configuration></configuration>`这对标签里配置。在这里记录一些课堂老师讲解的重要配置。


<configuration> 

1.配置日志开启日志通过```<settings></settings>```标签配置如下所示  

   <!-- 开启日志 -->  
    <settings>
      <setting name="logImpl" value="LOG4J"/>
    </settings>  

2.为了提高效率在mapper文件不用每个resultType属性里都添加包名设置别名设置在typeAliases标签里如下两种方式配置优点和缺点  

     <typeAliases>
        <typeAlia type="com.pojo.Student"alias="Student"/>--方法一 缺点有多少个类就得有多少行这个代码
         <!-- 或者<package name="com.pojo/>" --方法二 缺点 在pojo包下如果还有子包在子包下有与子包同级的类名相同时会出现歧义不知指定的是哪个包
      </typeAliases>

3.数据库连接的配置

  <environments default="default">
   <!--配置多个数据源,但只能指定一个使用  -->
     <!-- Mysql的数据库链接 -->
    <environment id="default">
       <transactionManager type="JDBC"/><!-- 指定当前数据库的事务管理方式 -->
       <dataSource type="POOLED"><!-- 数据源的管理方式为连接池 -->
       <property name="driver"   value="com.mysql.jdbc.Driver"/>
       <property name="url" value="dbc:mysql://localhost:3306/ssmLab4046?serverTimezone=GMT%2B8"/>
       <property name="username" value="root"/>
       <property name="password" value="1234"/>
     <!-- 设定数据库的链接4要素 -->
    </dataSource>
    </environment>   

4.映射文件的扫面通过标签配置。

 <!-- 一定是文件格式-->
    <mappers>
     <mapper resource="com/mapper/StudentMapper.xml"/>
    </mappers>

</configuration>  
<mapper></mapper>  

mapper文件配置以及对应方法的讲解

  1. mapper配置时设置的属性namespace定义一个操作包,是映射文件匹配的重要点;

    <mapper namespace="com.Mapper.Student">

  2. 插入时获取插入的主键
    insert into student(name,age,score) values(#{name},#{age},#{score}) select @@identity
    对应的方法是pojo类,不带主键的构造方法(service层的方法为):
    public void insertStudentCatchID(Student s) { if(session!=null){ session.insert(“com.Mapper.Student.insertStudentCatchID”, s); session.commit(); }
    }

    1. #和$的区别和使用

在传参过程中 #{}使用占位符的方式传参。${value}字符条件的拼接;在使用过程中,有一点很小的区别,#{xxx}需要用 '%'#{xxx}'%'包括起来,而${value}用'%${value}%'包起来.另为${vlaue}在万不得已的时候不推荐用,因为会造成SQL注入例如:

selete * from student 
      where id=#{xxx} or 1=1  
    假如这是登录验证就会产生SQL注入