Mybatis 注解

时间:2022-07-26
本文章向大家介绍Mybatis 注解,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1 基本使用

1.1.1 常用注解

注解

描述

@Insert

实现新增

@Update

实现更新

@Delete

实现删除

@Select

实现查询

@Result

实现结果集封装

@Results

可以与 @Result 一起使用,封装多个结果集

@One

实现一对一结果集封装

@Many

实现一对多结果集封装

1.1.2 MyBatis 增删改查

☞ 实体类

public class Student {
    private Long sId;
    private String sName;
    private Long sAge;
    private String sSex;
	
	// set and get

}

☞ DAO

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/9
 * @description Mybatis 注解
 */
public interface StudentDao {

    @Select("select * from student")
    public List<Student> findAll();

    @Select("select * from where s_id = #{id} ")
    public Student findOne(Long id);

    @Insert("insert into student values (#{sId}, #{sName}), #{sAge}, #{sSex}")
    public int insert(Student student);

    @Update("update from student set s_id = #{sId}, s_name = #{sName}, s_age = #{sAge}, s_sex = #{sSex}")
    public int update(Student student);
    
    @Delete("delete from student where s_id = #{id} ")
    public int delete(Long id);
}

☞ 配置文件

<typeAliases>
    <package name="com.software.mybatis.entity"/>
</typeAliases>

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/db"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>

<mappers>
	<!-- 指定接口所在的包 -->
    <package name="com.software.mybatis.dao"/>
	<!-- 指定接口 -->
    <mapper class="com.software.mybatis.dao.StudentDao"/>
</mappers>

☞ 测试

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/9
 * @description
 */
public class MybatisDemo {

    private StudentDao studentDao;

    @Before
    public void before() throws IOException {
        // 加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
        // 获得 sqlSession 工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        // 获得 sqlSession 对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 获取 mapper
        studentDao = sqlSession.getMapper(StudentDao.class);
    }

    @Test
    public void TestA() throws IOException {
        List<Student> studentList = studentDao.findAll();

        System.out.println(studentList);
    }

}

  我们可以看到,明明结果已经查询出来了,为什么打印出来却是空的。这个是因为属性名和列名不一致造成的,类似于我们这种 sId ☞ s_id 可以打开驼峰之自动转换。如果二者之间没有任何联系就需要使用 @Results 一一映射。

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
@Select("select * from student")
@Results(value = {
                @Result(property = "sId", column = "s_id"),
                @Result(property = "sName", column = "s_name"),
                @Result(property = "sAge", column = "s_age"),
                @Result(property = "sSex", column = "s_sex")
})
public List<Student> findAll();

1.2 复杂映射

1.2.1 注解详解

注解

说明

@Results

代替的是标签该注解中可以使用单个@Result注解,也可以使用@Result集合使用格式:@Results({@Result(),@Result()})或@Results(@Result())

@Result

代替了标签和标签@Result中属性介绍:column:数据库的列名property:需要装配的属性名one:需要使用的@One 注解(@Result(one=@One)()))many:需要使用的@Many 注解(@Result(many=@many)()))

@One(一对一)

代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。@One注解属性介绍:select:指定用来多表查询的sqlmapper使用格式:@Result(column="",property="".one=@One(select="))

@Many(一对多)

代替了标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。使用格式:@Result(property="".column=",many=@Many(select="))

1.2.2 一对一

☞ 实体类

public class Student {
    private Long sId;
    private String sName;
    private Long sAge;
    private String sSex;
    private Class class;

    // set and get
}
public class Class {
    private Long cId;
    private String cName;
    private String cAddr;

    // set and get
}

☞ DAO

public interface ClassDao {
    @Select("select * from class where c_id = #{id} ")
    public Class findById(Long id);
}
public interface StudentDao {

    @Select("select * from student")
    @Results({
            @Result(property = "sId", column = "s_id"),
            @Result(property = "sName", column = "s_name"),
            @Result(property = "sAge", column = "s_age"),
            @Result(property = "sSex", column = "s_sex"),
            // 类似于先查询出 student 然后拿 c_id 再去查 class
            @Result(property = "class", column = "c_id", javaType = Class.class,
            		one = @One(select = "com.software.mybatis.dao.ClassDao.findById"))
    })
    public List<Student> findAll();
}

1.2.3 一对多

☞ 实体类

public class Student {
    private Long sId;
    private String sName;
    private Long sAge;
    private String sSex;
    private Long cId;

    // set and get
}
public class Class {
    private Long cId;
    private String cName;
    private String cAddr;
    private List<Student> students;

    // set and get
}

☞ DAO

public interface StudentDao {
    @Select("select * from where c_id = #{id} ")
    public List<Student> findByCid(Long id);
}
public interface ClassDao {
    @Select("select * from class")
    @Results({
            @Result(property = "cId", column = "c_id"),
            @Result(property = "cName", column = "c_name"),
            @Result(property = "cAddr", column = "c_addr"),
            // 类似于先查询 class 然后使用 c_id 查询 student
            @Result(property = "students", column = "c_id", javaType = List.class,
                    many = @Many(select = "com.software.mybatis.dao.StudentDao.findByCid")),
    })
    public List<Class> findAll();
}

1.2.4 多对多

☞ 实体类

public class Course {
    private Integer cId;
    private String cName;
    private List<Student> students;
    
    // set and get
}
public class Student {
    private Integer sId;
    private String sName;
    private Long sAge;
    private String sSex;
    private List<Course> courses;
        
    // set and get
}

☞ DAO

public interface CourseDao {
    @Select("select * from course c, s_c sc where c.c_id = sc.c_id and sc.s_id = #{id} ")
    public List<Course> findBySid(Long id);
}
public interface StudentDao {
    @Select("select * from student")
    @Results({
            @Result(property = "sId", column = "s_id"),
            @Result(property = "sName", column = "s_name"),
            @Result(property = "sAge", column = "s_age"),
            @Result(property = "sSex", column = "s_sex"),
            // 类似于先查询 student 然后连接查询 course 和 s_c 表条件为 c.c_id = sc.c_id and s_id = sc.s_id
            @Result(property = "Courses", column = "s_id", javaType = List.class,
            		many = @Many(select = "com.software.mybatis.dao.CoursesDao.findBySid"))
    })
    public List<Student> findAll();
}