mybatis通过注解开发

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

1.简单的应用

接口:

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 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 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 selectUserReverse();
}

调用:

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 = 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 user1 = testMapper.selectUserByName("lyx");
            user1.forEach(System.out::println);

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

        }
    }
}

2.复杂查询

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

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

@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 getStudentByTid(int tid);

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


    
    
    
        
        
        
    

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

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);
}

你可能感兴趣的:(mybatis,oracle,数据库)