Mybatis配置解析
核心配置文件:mybatis-config.xml
属性(properties)
在resources目录下新建一个properties
文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF8
username=root
password=123456
在核心配置文件中引入:
<properties resource="db.properties">
</properties>
这样一来,我们的配置就可以写成这样:
<configuration>
<properties resource="db.properties">
</properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/skdjq/Dao/UserMapper.xml"/>
</mappers>
</configuration>
看到区别没?我们的value后面可以直接使用${}
从properties文件中读取到相关参数。
在引入时,我们也可以这样:
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
只不过这里重复属性最后生效的值是db.properties
里配置的属性。
属性优先级
如果一个属性在不只一个地方进行了配置,那么,MyBatis 将按照下面的顺序来加载:
- 首先读取在 properties 元素体内指定的属性。
- 然后根据 properties 元素中的 resource 属性读取类路径下属性文件,或根据 url 属性指定的路径读取属性文件,并覆盖之前读取过的同名属性。
- 最后读取作为方法参数传递的属性,并覆盖之前读取过的同名属性。
因此,通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的则是 properties 元素中指定的属性。
常见错误
若出现上图所示错误,说明的引入位置出错,理论上必须放在最上面,也就是紧跟``下面。
别名
别名用来减少类完全限定名的冗余,如:
<select id="getUserList" resultType="com.skdjq.pojo.User">
select * from mybatis.user;
</select>
中的com.skdjq.pojo.User
就太过冗余了。
起别名有两种方式:
第一种:
<typeAliases>
<typeAlias type="com.skdjq.pojo.User" alias="User"/>
</typeAliases>
第二种:
<typeAliases>
<package name="com.skdjq.pojo"/>
</typeAliases>
扫描实体类的包,默认别名为这个包下实体类的类名(首字母小写)。
- 在实体类比较少的时候,使用第一种
- 如果实体类比较多,使用第二种
属性名和字段名不一致的问题
当实体类中定义的属性和数据库里的字段不一致时,会发生冲突。
如:
实体类User属性为id
,name
,password
:
public class User {
private int id;
private String name;
private String password;
}
数据库里的字段名为id
,name
,pwd
:
这时候再执行sql操作就会出现问题,那么我们如何解决呢?
解决方法一:
- 起别名(不推荐):
由
<select id="getUserList" resultType="User">
select * from mybatis.user;
</select>
变为:
<select id="getUserList" resultType="User">
select id,name,pwd as password from mybatis.user;
</select>
resultMap(推荐)
结果集映射:
比如:
将resultType改为resultMap:
<!--id任取,type是实体类-->
<resultMap id="UserMap" type="com.skdjq.pojo.User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="pwd" property="password"/>
</resultMap>
<!--resultMap为上面的id-->
<select id="getUserList" resultMap="UserMap">
select * from mybatis.user;
</select>