Spring boot中MyBatis xml和dao层接口组合使用出现的错误

在编写头条资讯网站时,遇到重大问题:

MyBatis xml和dao层接口组合使用,一共有三种方法 具体见此文MyBatis xml和dao层接口组合使用

 

本文主要是在NewsDAO 中的查询语句出错

出错时,采用的方法是 xml+dao



dao代码的位置位于:src/java/com/my/toutiao/dao/NewsDAO
NewsDAO出错的代码如下:

@Mapper
@Repository
public interface NewsDAO {
    String TABLE_NAME = "news";
    String INSERT_FIELDS = " title, link, image, like_count, comment_count, created_date, user_id ";
    String SELECT_FIELDS = " id, " + INSERT_FIELDS;

    @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS,
            ") values (#{title},#{link},#{image},#{likeCount},#{commentCount},#{createdDate},#{userId})"})
    int addNews(News news);

    //出错点在此
    List<News> selectByUserIdAndOffset(@Param("userId") int user_id,
                                       @Param("offset") int offset,
                                       @Param("limit") int limit);
}

xml 代码的位置位于:src/resources/com/my/toutiao/dao/NewsDAO.xml
xml源码如下:

<?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" >
<mapper namespace="com.my.toutiao.dao.NewsDAO">
    <sql id="table">news</sql>
    <sql id="selectFields">id,title, link, image, like_count, comment_count,created_date,user_id
    </sql>
    <select id="selectByUserIdAndOffset" resultType="com.my.toutiao.model.News">
        SELECT
        <include refid="selectFields"/>
        FROM
        <include refid="table"/>

        <if test="userId != 0">
            WHERE user_id = #{userId}
        </if>
        ORDER BY id DESC
        LIMIT #{offset},#{limit}
    </select>
</mapper>

 

首先,确定xml的位置处于和DAO的路径相对应
检查mapper,namespace,是否和原DAO包路径一致,resultType是否是对应的返回值,select id是否为选定的方法


在调用 selectByUserIdAndOffset 方法时,不断出错,出现一种错误改正后又出现另一种错误,大概以下几种错误:


一:找不到数据库匹配

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

尝试方法:在运行的 ToutiaoApplication.class文件中的@SpringBootApplication改为:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
出现新错误

二:Spring注入问题

org.springframework.beans.factory.UnsatisfiedDependencyException: 
        Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'newsService'; nested exception is 
        org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'newsService': Unsatisfied dependency expressed through field 'newsDAO'; 
        nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'newsDAO' defined in file 
        [H:\JavaWeb\toutiao\target\classes\com\my\toutiao\dao\NewsDAO.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

大意是Spring bean无法装配,中间伴随有DAO层无法正常注解


1.确保了ToutiaoApplication在最顶层包中,失败;
2.在ToutiaoApplication.class中加入注解:@MapperScan("com.my.toutiao.dao"),失败;
3.检查了target中对应目录下是否生成了.xml文件,存在,同时也使用以下代码确保可以正常加载.xml(放在pom.xml的build中)
 

   <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>


失败;

通过反复尝试多种方法后,无效,暂未解决最终,尝试从根本解决问题:在dao层使用注解,NewsDAO代码改为下

@Mapper
@Repository
public interface NewsDAO {
    String TABLE_NAME = "news";
    String INSERT_FIELDS = " title, link, image, like_count, comment_count, created_date, user_id ";
    String SELECT_FIELDS = " id, " + INSERT_FIELDS;

    @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS,
            ") values (#{title},#{link},#{image},#{likeCount},#{commentCount},#{createdDate},#{userId})"})
    int addNews(News news);

    //    更正后代码
    @Select({"select " + SELECT_FIELDS + " from " + TABLE_NAME + " where user_id=#{userId} " +
            "ORDER BY id DESC LIMIT #{offset} , #{limit}"})
    List<News> selectByUserIdAndOffset(@Param("userId") int user_id,
                                       @Param("offset") int offset,
                                       @Param("limit") int limit);
}

同时删去resources下对应的.xml文件
如果代码出现如下错误:

org.mybatis.spring.MyBatisSystemException: nested exception is 
org.apache.ibatis.binding.BindingException: Parameter 'userId' not found.
     Available parameters are [0, 1, 2, param3, param1, param2]

说明 在selectByUserIdAndOffset方法中没有使用@Param("userId") int user_id定义变量,使用了int user_id,更正即可

此次错误花了快十个小时尚未解决,期间重构了一遍工程项目,但是发生了同样的错误,使用这种方法,没有从根本上解决问题,需要继续学习,待以后完善。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值