MyBatis配置文件优化

一、连接数据库的配置单独放在一个properties文件中
之前,我们直接将数据库的连接配置信息写在了MyBatis的conf.xml文件中,其实我们完全可以将数据库的连接配置信息写在一个properties文件中,然后在conf.xml文件中引用,具体做法如下:
1.在src下新建db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql
username=root
password=######
2.在conf.xml中引用db.properties:
<properties resource="db.properties"/>
。。。。。。。。。。。。。。。
<dataSource type="POOLED">
        <property name="driver" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
</dataSource>

二、为实体类定义别名,简化SQL映射XML文件中的引用
之前,我们在SQL映射XML文件中引用实体类时,需要写上实体类的全类名,如:
parameterType="com.domain.Student",每次都写这么一长串内容比较麻烦,而我们希望能够简写成下面的形式:
parameterType="_Student",为了达到这种效果,需要在conf.xml中为实体类Student定义一个别名_Student:
<typeAliases>
        <!-- 为实体类Student配置一个别名_Student -->
        <!-- <typeAlias type="com.domain.Student" alias="_Student"/> -->
        <!-- 为com.domain包下的所有实体类配置别名,MyBatis默认的配置别名的方式就是去除类所在的包后的简单类名 -->
        <package name="com.domain"/>
</typeAliases>

注:typeAliases需要写到conf.xml文件的上方,否则会报错。

猜你喜欢

转载自www.cnblogs.com/yuanfei1110111/p/10349708.html