SpringBoot + MyBatis,注解和xml

起因

最近写代码,使用MyBatis连接数据库,却总是扫描不要mapper.xml 文件。临时用注解的方式解决了问题。后面又转过头来,用xml文件实现了一次。

注解方式

例如,我在dao中,实现一个查询账号密码的语句:

@Mapper
public interface LoginDao{
     /*
    * 根据username和password查询
    * 如果账号密码正确,返回为1 
    * */
	@Select("select count(*) from account where username=#{username} and password=#{password}")
    public int resultValue(@Param("username") String username, @Param("password")String password);
}

除了@Select 还有 @Delete,@Update,@Insert。

注解的方式,不需要指定扫描mapper.xml 文件。

xml方式

在Dao中的代码,去掉@Select这一行即可。

我将mapper.xml 文件是放在resources/mapper/ 下。为了能够扫描到该文件,应该在SpringBoot的 application.properties 中指定扫描,添加信息如下:

mybatis.mapperLocations=classpath*:mapper/*.xml

P.S. classpath* 和 classpath 的区别,有兴趣的可以去查一下。本文不过多阐述。

这样就可以扫描到了。

然后可以去填写mapper.xml文件了。这里我的xml文件命名为LoginDao.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.xxx.xxx.dao.LoginDao">
    <select id="resultValue" resultType="int">
        select count(username) from account where username=#{username} and password=#{password}
    </select>
</mapper>

P.S. namespace一定要填写。

说明

经过以上的两种方式,都是可以实现的。

但是一般而言,xml的可维护性可能会更好。一般自己写着玩可以用注解,一旦SQL语句多了起来就是相当的麻烦了。

因此,我个人比较推荐的是使用xml的方式来写mybatis。

猜你喜欢

转载自blog.csdn.net/qq_42670048/article/details/86219675