mybatis通过注解开发

MyBatis支持通过注解来进行数据库操作,这种方式称为MyBatis的注解开发(Annotation-Based Development)。通过注解,可以在Java接口或类上直接标注SQL语句,避免了在XML文件中编写相应的SQL映射。

1.简单的应用

接口:

java 复制代码
package Mybatis.annotation;

import Mybatis.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * MyBatis Mapper interface for handling User-related database operations.
 */
public interface StudentMapper {

    /**
     * Retrieves a list of all users from the 'accounting_ledger.user' table.
     *
     * @return List of User objects.
     */
    @Select("SELECT * FROM accounting_ledger.user")
    List<User> selectUser();

    /**
     * Retrieves a list of users with a specific username from the 'accounting_ledger.user' table.
     *
     * @param username The username to search for.
     * @return List of User objects matching the specified username.
     */
    @Select("SELECT * FROM accounting_ledger.user WHERE username=#{username}")
    List<User> selectUserByName(String username);

    /**
     * Retrieves a list of all users from the 'accounting_ledger.user' table,
     * reversing the mapping of username and password.
     *
     * @return List of User objects with reversed username and password.
     */
    @Results({
            @Result(column = "username", property = "password"),
            @Result(column = "password", property = "username")
    })
    @Select("SELECT * FROM accounting_ledger.user")
    List<User> selectUserReverse();
}

调用:

java 复制代码
package Mybatis.annotation;

import Mybatis.Mapper.MyBatisUtil;
import Mybatis.Mapper.UserMapper;
import Mybatis.User;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class Main5 {
    public static void main(String args[]){
        //用MyBatisUtil来包装之前Main1的工厂类,更简单地得到连接
        try(SqlSession sqlSession = MyBatisUtil1.getSession(true)){
            //获取接口的实现类`
            StudentMapper testMapper = sqlSession.getMapper(StudentMapper.class);
            //通过接口来实现sql语句
            List<User> user = testMapper.selectUser();

            //这行代码使用了 Java 8 引入的新特性之一,称为方法引用(Method Reference)。
            // 具体来说,System.out::println 是一个静态方法引用,用于将 println 方法关联到 System.out 对象上。
            //在这里,System.out::println 等效于 lambda 表达式 (s) -> System.out.println(s)。
            // 它表示将遍历 student 集合的每个元素,并将每个元素传递给 System.out.println 方法,实现在控制台上打印每个元素的效果。
            user.forEach(System.out::println);
            System.out.println();

            List<User> user1 = testMapper.selectUserByName("lyx");
            user1.forEach(System.out::println);

            List<User> user2 = testMapper.selectUserReverse();
            user2.forEach(System.out::println);

        }
    }
}

2.复杂查询

如何使用注解来完成复杂查询呢?我们设想这样的情况:一个老师教授很多学生,所以对于这个老师类,我们使用一个list来装所有上这个老师课的学生。那么对于这个list,我们需要选择出所有上个这个老师课的学生,所以我们出现了many标签。

many标签可以指定一个也写在这个接口里的子语句(getStudentByTid),然后将这个子语句的返回结果存入指定的集合字段(column = "tid", property = "studentList")。

java 复制代码
@Results({
        @Result(id = true, column = "tid", property = "tid"),
        @Result(column = "name", property = "name"),
        @Result(column = "tid", property = "studentList", many =
            @Many(select = "getStudentByTid")
        )
})
@Select("select * from teacher where tid = #{tid}")
Teacher getTeacherBySid(int tid);

@Select("select * from student inner join teach on student.sid = teach.sid where tid = #{tid}")
List<Student> getStudentByTid(int tid);

我们发现,多出了一个子查询,而这个子查询是单独查询该老师所属学生的信息,而子查询结果作为@Result注解的一个many结果,代表子查询的所有结果都归入此集合中(column = "tid", property = "studentList"的这个集合)(也就是之前xml的collection标签)

XML 复制代码
<resultMap id="asTeacher" type="Teacher">
    <id column="tid" property="tid"/>
    <result column="tname" property="name"/>
    <collection property="studentList" ofType="Student">
        <id property="sid" column="sid"/>
        <result column="name" property="name"/>
        <result column="sex" property="sex"/>
    </collection>
</resultMap>

同理,@Result也提供了@One子注解来实现一对一的关系表示,类似于之前的assocation标签,考虑如下情况:通过id获取用户的profile(profile包含很多个子字段)

java 复制代码
public class User {
    private Long id;
    private String username;
    private UserProfile profile;  // One-to-One relationship with UserProfile

    // Getters and setters...
}

public class UserProfile {
    private Long userId;
    private String fullName;
    private String email;

    // Getters and setters...
}

// MyBatis Mapper interface
public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "username", column = "username"),
        @Result(property = "profile", column = "id", one = @One(select = "getUserProfile"))
    })
    User getUserById(Long id);

    @Select("SELECT * FROM user_profiles WHERE user_id = #{userId}")
    UserProfile getUserProfile(Long userId);
}
相关推荐
2301_8002561118 小时前
第九章:空间网络模型(空间网络查询、数据模型、Connected、with Recursive、pgRouting)
网络·数据库·算法·postgresql·oracle
霖霖总总19 小时前
[小技巧19]MySQL 权限管理全指南:用户、角色、授权与安全实践
数据库·mysql·安全
heartbeat..1 天前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
麦聪聊数据1 天前
MySQL并发与锁:从“防止超卖”到排查“死锁”
数据库·sql·mysql
AC赳赳老秦1 天前
DeepSeek 私有化部署避坑指南:敏感数据本地化处理与合规性检测详解
大数据·开发语言·数据库·人工智能·自动化·php·deepseek
YMatrix 官方技术社区1 天前
YMatrix 存储引擎解密:MARS3 存储引擎如何超越传统行存、列存实现“时序+分析“场景性能大幅提升?
开发语言·数据库·时序数据库·数据库架构·智慧工厂·存储引擎·ymatrix
辞砚技术录1 天前
MySQL面试题——索引2nd
数据库·mysql·面试
linweidong1 天前
C++thread pool(线程池)设计应关注哪些扩展性问题?
java·数据库·c++
欧亚学术1 天前
突发!刚刚新增17本期刊被剔除!
数据库·论文·sci·期刊·博士·scopus·发表
oMcLin1 天前
如何在Oracle Linux 8.4上搭建并优化Kafka集群,确保高吞吐量的实时数据流处理与消息传递?
linux·oracle·kafka