Mapper层注解讲解
1 Mapper层注解
Mapper
层注解@Reponsitory
和@Mapper
经常使用但是不知道区别,就学习记录下
1.1 @Repository
@Repository
:@Repository
的作用与@Controller
,@Service
的作用都是把对象交给Spring
管理。@Repository
是标注在Dao
层接口上,作用是将接口的一个实现类交给Spring
管理。
注意
:
- 使用这个注解的前提是必须在启动类上添加
@MapperScan("Mapper接口层路径")
注解
这个@Repository
完全可以省略不写,也完全可以实现自动注入,但是在IDEA
中会存在一个红色的波浪线。原因如下:
Spring
配置文件中配置了MapperScannerConfiguer
这个Bean
,它会扫描持久层接口创建实现类并交给Spring
管理。SpringBoot
的启动类上标注了@MapperScan
,它的作用和上面的MapperScannerConfiguer
作用一样
1.2 @Mapper
@Mapper
: 这个注解一般使用在Dao
层接口上,相当于一个mapper.xml
文件,它的作用就是将接口生成一个动态代理类。加入了@Mapper
注解,目的就是为了不再写mapper
映射文件。这个注解就是用来映射mapper.xml
文件的。
使用@mapper
后,不需要在spring
配置中设置扫描地址,通过mapper.xml
里面的namespace
属性对应相关的mapper
类,spring
将动态的生成Bean
后注入到ServiceImpl
中
注意
:
在Dao
层不要存在相同名字的接口,也就是在Dao
不要写重载。因为mapper
文件是通过id
与接口进行对应的,如果写了两个同名的接口,就会导致mapper
文件映射出错。
1.3 @Mapper和@MapperScan区别
@Mapper
注解写在每个Dao
接口层的接口类上,@MapperScan
注解写在SpringBoot
的启动类上。
当我们的一个项目中存在多个Dao
层接口的时候,此时我们需要对每个接口类都写上@Mapper
注解,非常的麻烦,此时可以使用@MapperScan
注解来解决这个问题。让这个接口进行一次性的注入,不需要在写@Mapper
注解
@SpringBootApplication
@MapperScan("cn.gyyx.mapper")
// 这个注解可以扫描 cn.gyyx.mapper 这个包下面的所有接口类,可以把这个接口类全部的进行动态代理。
public class WardenApplication {
public static void main(String[] args) {
SpringApplication.run(WardenApplication.class,args);
}
}
@Mapper
注解相当于是@Reponsitory
注解和@MapperScan
注解的和,会自动的进行配置加载。
@MapperScan
注解多个包,@Mapper
只能把当前接口类进行动态代理。
在实际开发中,如何使用@Mapper、@MapperSacn、@Repository
注解
- 在
SpringBoot
的启动类上给定@MapperSacn
注解。此时Dao
层可以省略@Mapper
注解,当然@Repository
注解可写可不写,最好还是写上。
当使用@Mapper
注解的时候,可以省略@MapperSacn
以及@Repository
。
建议:
- 以后在使用的时候,在启动类上给定
@MapperScan("Dao层接口所在的包路径")
。在Dao
层上不写@Mapper
注解,写上@Repository
即可
1.4 动态SQL注解
MyBatis
的动态SQL
注解开发是基于Java注解和接口方法的,通过在接口方法上使用注解,可以在运行时生成对应的SQL
语句。MyBatis
会根据接口方法的注解来生成SQL
,并将它们与数据库进行交互。它可以在实体类或映射文件中使用注解来配置映射关系。常用的注解包括 @Select、@Update、@Insert、@Delete
等,它们分别用于配置查询、更新、插入和删除操作。通过这些注解,我们可以直接在实体类或映射文件中定义 SQL 语句,而不需要像传统的 MyBatis 配置方式那样在映射文件中使用 <select>、<update>、<insert> 和 <delete>
标签来定义 SQL 语句
1.4.1 @Select
1.4.1.1 基本用法
@Select
:该注解的目的是为了取代mapper.xml
中的select
标签,只作用于方法上面。此时就不要在写mapper.xml
文件了。
@Select
注解的源码
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select
{
String[] value();
}
从上述可以看到两点信息:
@Select
注解只能修饰方法。
@Select
注解的值是字符数组。
所以,@Select
注解的用法是这样的:
@Select({ "select * from xxx", "select * from yyy" })
Person selectPersonById(Integer id);
虽然@Select
注解的值是字符数组,但是真正生效的应该是最后那条SQL语句
1.4.1.2 @Select注解动态SQL拼写
普通的字符串值,只能实现变量的替换功能,实现简单的SQL
语句,如下所示
@Select("select * from t_person where id = #{id}")
Person selectPersonById(Integer id);
如果要想实现复杂的逻辑判断,则需要使用标签 ,如下所示:
@Select("<script> select * from t_person where id = #{id}
<when test='address !=null'> and address = #{address}
</when> </script>")
Person selectPersonById(Integer id);
其实,标签 注解专用的,其他的注解,例如@Insert、@Update、@Delete等等,都可以使用的。
1.4.2 与@Select相关注解
import java.util.List;
import me.gacl.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/**
* @author gacl
* 定义sql映射的接口,使用注解指明方法要执行的SQL
*/
public interface UserMapperI {
使用@Insert注解指明add方法要执行的SQL
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int add(User user);
使用@Delete注解指明deleteById方法要执行的SQL
@Delete("delete from users where id=#{id}")
public int deleteById(int id);
使用@Update注解指明update方法要执行的SQL
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int update(User user);
使用@Select注解指明getById方法要执行的SQL
@Select("select * from users where id=#{id}")
public User getById(int id);
使用@Select注解指明getAll方法要执行的SQL
@Select("select * from users")
public List<User> getAll();
}
1.4.3 动态SQL查询
动态SQL查询
通常用于根据不同条件构建SQL
语句。
在这个示例中,我们将演示如何构建一个动态查询,根据传递的参数来动态生成查询条件。首先,创建一个 UserProvider
类,用于提供动态SQL
查询的逻辑:
import org.apache.ibatis.jdbc.SQL;
import java.util.Map;
public class UserProvider {
public String dynamicSQL(Map<String, Object> params) {
return new SQL() {
{
SELECT("*");
FROM("users");
if (params.get("username") != null) {
WHERE("username = #{username}");
}
if (params.get("email") != null) {
WHERE("email = #{email}");
}
}
}.toString();
}
}
在Mapper
接口中,使用 @SelectProvider
注解来指定动态SQL
的提供者类和方法。
@SelectProvider(type = UserProvider.class, method = "dynamicSQL")
List<User> searchUsers(UserCriteria criteria);
在这里,UserProvider
类的 dynamicSQL
方法会根据传递的 criteria
参数动态生成SQL
查询语句,实现了根据用户名和电子邮件地址查询用户的功能。
MyBatis
动态注解开发是一种强大的方式,能够根据不同条件动态生成SQL
语句,无需编写繁琐的XML
映射文件,可以在接口方法上直接使用注解,减少了冗余的代码。它提供了灵活性和简洁性,适用于各种不同的数据库操作需求。
1.5 @Param
接口绑定解决多参数的传递,一般使用@Param
@Param
: 动态代理接口向映射文件中传递参数的时候,会使用@Param
注解,并且如果动态代理接口使用了@Param
这个注解,那么映射文件中的标签中可以不用写parameterType
属性,可以直接接收@Param
中传递来的参数值
1.5.1 @Param注解基本类型的参数
mapper中的方法:
public User selectUser(@Param("userName") String name,@Param("password") String pwd);
映射到xml
中的标签
<select id="selectUser" resultMap="User">
select * from user where user_name = #{userName} and user_password=#{password}
</select>
其中where user_name = #{userName} and user_password = #{password}
中的userName
和password
都是从注解@Param()
里面取出来的,取出来的值就是方法中形式参数 String name
和 String pwd
的值。
重点:当只存在一个参数的时候,此时可以省略这个@Param
注解,但是两个参数必须使用这个注解。
1.5.2 @Param注解JavaBean对象
SQL
语句通过@Param
注解中的别名把对象中的属性取出来然后复制 mapper
中的方法:
public List<User> getAllUser(@Param("user") User u);
映射到xml
中的标签
<select id="getAllUser" parameterType="com.vo.User" resultMap="userMapper">
select
from user t where 1=1
and t.user_name = #{user.userName}
and t.user_age = #{user.userAge}
</select>
注意:
当使用了@Param
注解来声明参数的时候,SQL
语句取值使用#{}
,${}
取值都可以。
当不使用@Param
注解声明参数的时候,必须使用的是#{}
来取参数。使用${}
方式取值会报错。
不使用@Param
注解时,参数只能有一个,可以是一个基本的数据也可以是一个JavaBean
1.5.3 不使用@Param
接口绑定解决多参数的传递,如果不使用@Param
,则使用数字的方式取出,从0
开始
接口中定义方法
User selByUP(String username, String password
映射文件中提供对应的标签
此时, SQL
语句中获取方式有两种, 通过#{index}
或#{param+数字}
的方式
<select id="selByUP" resultType="user">
select * from t_user where username=#{0} and password=#{1}
</select>
或者
<select id="selByUP" resultType="user">
select * from t_user where username=#{param1} and password=#{param2}
</select>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了