美文网首页
Mybatis入门 案例----基础搭建(二)

Mybatis入门 案例----基础搭建(二)

作者: 睡前听卡农 | 来源:发表于2021-09-07 20:59 被阅读0次
回顾:上个内容我们使用配置文件进行了一个简单的搭建,那么有几个问题

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>

在映射文件中就直接随便起个名字,我这里就叫goods

<select id="selectAll" resultType="goods">
        select * from goods;
    </select>

2.如果数据库中的表字段和实体类中的字段不一致呢?

这里,我首先把数据库中的表名修改一个字段,我把gname修改为name


这个问题经常遇到,那就是封装的实体类对象中的属性和表字段不一致,其实解决方法很多,我们常用的就是起别名和使用resultMap

  • 1、就是在sql语句中将字段名称修改为和属性名一致的,修改GoodsMapper.xml
<select id="selectAll" resultType="goods">
    select id,type,price,name as gname,description from goods;
</select>

这种方法缺点也很明显,那就是如果字段过多的时候写起来很麻烦。

  • 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一般使用注解,复杂的可以考虑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();

}

这就是对上次搭建的遗留的问题进行解决的方案,以后会越来越方便,但是我们还是需要了解其中的思想。

相关文章

网友评论

      本文标题:Mybatis入门 案例----基础搭建(二)

      本文链接:https://www.haomeiwen.com/subject/rnwpwltx.html