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);
}
相关推荐
tiancaijiben11 小时前
阿里云SSL证书自动续签与部署完全指南:从托管服务到开源工具全方案解析
数据库
全堆鸿蒙11 小时前
25 数据库设计与表结构规划:5 张表的设计思路
数据库·华为·cocoa·harmonyos
笃行35011 小时前
【金仓数据库产品体验官】_坏得起_实测:备份恢复、PITR 时间穿越与主备切换——KingbaseES V9R3C18 深度体验(三)
数据库
笃行35013 小时前
从兼容到进阶:驱动直连、窗口函数与动态 SQL 实测——KingbaseES V9R3C18 深度体验(二)
数据库
笃行35014 小时前
MySQL 的 JSON 字段迁到金仓还能用吗?——KingbaseES V9R3C18 JSON 操作符与函数兼容实测
数据库
IpdataCloud15 小时前
跨境AI金融风险怎么防?IP风险画像的实战应用指南
数据库·tcp/ip·金融·ip
Alan_7517 小时前
API 接口慢调用根因定位:从 TCP 建连到数据库 IO 的全栈排查实战
数据库
多巴胺梦想家17 小时前
事务与并发控制:当多人同时操作数据库
服务器·数据库·oracle
howard200518 小时前
PostgreSQL起步
数据库·postgresql
秋田君19 小时前
QT_QT布局详解
开发语言·数据库·qt