回顧:上個內(nèi)容我們使用配置文件進行了一個簡單的搭建,那么有幾個問題
1.什么是包掃描?什么是起別名?
1、首先,包掃描可以不用指定資源文件,而是掃描包下面的文件。
例如:在mybatis-config.xml中的映射文件
<mappers>
<!-- 這里是映射到GoodsMapper.xml文件中-->
<!-- <mapper resource="com/ppf/mapper/GoodsMapper.xml"/>-->
<package name="com.ppf.mapper"/>
</mappers>
- 注意:這里只有一個GoodsMapper.xml文件,但是如果有多個呢?
<mapper resource="com/ppf/mapper/xxxxxMapper.xml"/>
<mapper resource="com/ppf/mapper/yyyyyMapper.xml"/>
<mapper resource="com/ppf/mapper/zzzzzMapper.xml"/>
是不是就要寫成如上這種形式?是不是很繁瑣,使用包掃描直接掃描mapper文件夾下的文件就可以。
2、起別名就是不用在映射文件中寫全類限定名
在mybatis-config.xml中寫在configuration下
<typeAliases>
<package name="com.ppf.pojo"/>
</typeAliases>
在映射文件中就直接隨便起個名字,我這里就叫g(shù)oods
<select id="selectAll" resultType="goods">
select * from goods;
</select>
2.如果數(shù)據(jù)庫中的表字段和實體類中的字段不一致呢?
這里,我首先把數(shù)據(jù)庫中的表名修改一個字段,我把gname修改為name


這個問題經(jīng)常遇到,那就是封裝的實體類對象中的屬性和表字段不一致,其實解決方法很多,我們常用的就是起別名和使用resultMap
- 1、就是在sql語句中將字段名稱修改為和屬性名一致的,修改GoodsMapper.xml
<select id="selectAll" resultType="goods">
select id,type,price,name as gname,description from goods;
</select>
這種方法缺點也很明顯,那就是如果字段過多的時候?qū)懫饋砗苈闊?/p>
- 2、使用resultMap將屬性和字段名稱映射起來,哪個不一樣就寫哪一個
<?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">
<!--這里的namesapce是唯一的命名空間,這里與接口保持一致-->
<mapper namespace="com.ppf.mapper.GoodsMapper">
<resultMap id="goods" type="Goods">
<result property="gName" column="name"></result>
</resultMap>
<select id="selectAll" resultMap="goods">
select * from goods;
</select>
</mapper>
3.如何使用注解代替xml文件?
xml文件可以和注解配合使用,但是簡單sql一般使用注解,復(fù)雜的可以考慮xml文件
package com.ppf.mapper;
import com.ppf.pojo.Goods;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface GoodsMapper {
@ResultMap("goods")
@Select("select * from goods")
List<Goods> selectAll();
}
這就是對上次搭建的遺留的問題進行解決的方案,以后會越來越方便,但是我們還是需要了解其中的思想。