【Mybatis系列】常用的全局配置标签

在我们开发的过程中使用mybatis-config.xml来配置关于mybatis的属性,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息,下面我来介绍两个个常用的配置:

一、properties

        properties可以用来引入一个外部配置文件,我们在开发过程中最常用的就是引用数据库的配置文件,

我们一般会在resource文件下创建db.properites文件来进行配置数据库

db.username=root
db.password=123
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql:///test?

然后我们在mybatis-config.xml文件中想要引用数据库配置信息,这个时候我们就用到了<properties>

<configuration>
    <properties resource="db.properties"></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="org.javaboy.mybatis.mapper"/>
    </mappers>
</configuration>

二、typeAlias

   主要用来定义别名,分为两种,一种是Mybatis自带的别名,另外一种就是我们自定义的实体类

  下面我主要说的就是自定义的:

  在我们没有使用typeAlias之前我们在mapper.xml文件中需要写类的全路径

<select id="getUserList" resultType="com.hyf.pojo.User">
  select * from user
 </select>

这样比较麻烦,于是我们在mybatis-config.xml文件中添加别名

<configuration>
    <typeAliases>
        <typeAlias type="com.hyf.pojo.User" alias="User"></typeAlias>
    </typeAliases>

</configuration>

给User类起的别名就是User,这样在mapper.xml文件中就可以直接用User来替代全路径,如下:

<select id="getUserList" resultType="User">
  select * from user
 </select>

但是这样还有一个缺点就是如果我们的实体类特别多,难道我们需要一个一个的去定义别名吗?这样就太过麻烦了,

我们除了上面的这种别名设置方式还有一种方式就是批量定义

       利用包扫描来做,批量定义默认的类的别名,是类名首字母小写

<configuration>
    <typeAliases>
        <package name="com.hyf.pojo"/>
    </typeAliases>

</configuration>

这样就给pojo下的所有实体类都定义了默认的别名

<select id="getUserList" resultType="user">
  select * from user
 </select>

猜你喜欢

转载自blog.csdn.net/qq_30631063/article/details/108203883
今日推荐