SpringBoot + MyBatis,注解和xml

本文对比了在MyBatis中使用注解和XML两种方式来定义数据库操作语句的方法。通过实例展示了如何在DAO接口中使用@Select等注解进行快速开发,并解释了如何在application.properties中配置扫描mapper.xml文件,以实现更灵活和可维护的数据库操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

起因

最近写代码,使用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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值