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);
}
相关推荐
阿华的代码王国12 分钟前
MySQL ------- 索引(B树B+树)
数据库·mysql
Hello.Reader40 分钟前
StarRocks实时分析数据库的基础与应用
大数据·数据库
执键行天涯42 分钟前
【经验帖】JAVA中同方法,两次调用Mybatis,一次更新,一次查询,同一事务,第一次修改对第二次的可见性如何
java·数据库·mybatis
yanglamei19621 小时前
基于GIKT深度知识追踪模型的习题推荐系统源代码+数据库+使用说明,后端采用flask,前端采用vue
前端·数据库·flask
工作中的程序员1 小时前
ES 索引或索引模板
大数据·数据库·elasticsearch
严格格1 小时前
三范式,面试重点
数据库·面试·职场和发展
工业甲酰苯胺1 小时前
Spring Boot 整合 MyBatis 的详细步骤(两种方式)
spring boot·后端·mybatis
微刻时光2 小时前
Redis集群知识及实战
数据库·redis·笔记·学习·程序人生·缓存
单字叶2 小时前
MySQL数据库
数据库·mysql
mqiqe2 小时前
PostgreSQL 基础操作
数据库·postgresql·oracle