Mapper层注解讲解

发布时间 2024-01-07 11:56:23作者: DoubleLi

 

 

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的启动类上标注了@MapperScanner,它的作用和上面的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}中的userNamepassword都是从注解@Param()里面取出来的,取出来的值就是方法中形式参数 String nameString 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>