一、入门
1.简介:
Mybatis提供了一些基础的注解,方便开发者减少XML使用。配合Mybatis配置中驼峰命名法自动映射配置,能更好的发挥Mybatis。对于一些复杂的场景建议使用XML,XML更加灵活。
2.基础注解
2.1 @Select:查询
@Select("SELECT 查询字段 FROM 表名 WHERE 字段名 = #{条件值}")
List<实体类> 方法名称(int 条件值);
@Select("SELECT * FROM job_apply_for WHERE post_id = #{postId}")
List<JobApplyFor> selectByPostId(int postId);
2.2 @Update:修改
@Update("UPDATE 表名 SET 修改字段 = #{修改后值} WHERE 条件字段 = #{条件值}")
int 方法名称(int 修改后值,int 条件值);
@Update("UPDATE job_apply_for SET status = #{status} WHERE apply_id = #{applyId}")
int updateStatus(int applyId,int status);
2.3 @Insert :新增
@Insert("新增语句")
int insert(实体类 实体类名称);
@Insert("insert into job_apply_for(post_id,person_info_id,department_id,apply_date,apply_reason,apply_status,apply_result,deadline_id) " +)
void insert(JobApplyFor jobApplyFor);
2.4 @Delete :删除
@Delete("delete from 表名 where 条件字段 = #{条件值}")
int 方法名称(Integer 条件值);
@Delete("delete from job_apply_for where apply_id = #{applyId}")
int deleteByApplyId(Integer applyId);
2.4 以上所有注解的基础语法
@Select("SQL")
@Delete("SQL")
@Update("SQL")
@Insert("SQL")
二、@Select查询进阶使用
2.1带参查询
@Select("SELECT 查询字段 FROM 表名 WHERE 字段名 = #{条件值}")
List<实体类> 方法名称(int 条件值);
@Select("SELECT * FROM job_apply_for WHERE post_id = #{postId}")
List<JobApplyFor> selectByPostId(int postId);
2.2一对一链表查询 One(注意需要在连接表的Mapper层写一个带外键查询)
@Select("查询全部SQL")
@Results({@Result(property = "需要连接的表名", column = "需要连接的表名外键", one = @One(select = "连接表带参查询语句"))})
User 方法名();
@Select("SELECT * FROM 需要连接的表名 WHERE 外键Id字段 = #{外键Id字段}")
Profile 方法名(@Param("外键Id字段") Integer 外键Id字段);
public interface UserMapper {
@Select("SELECT * FROM users")
@Results({
@Result(property = "profile", column = "user_id", one = @One(
select = "selectProfileById"
))
})
User getUserById();
}
public interface UserMapper {
// ... 其他方法 ...
@Select("SELECT * FROM profiles WHERE user_id = #{id}")
Profile selectProfileById(@Param("id") Integer id);
}
//实体类
public class User {
private Integer id;
private String name;
// 省略其他属性和 getter/setter 方法
private Profile profile; // 一对一关联
}
public class Profile {
private Integer id;
private String address;
// 省略其他属性和 getter/setter 方法
}
2.3一对多链表查询 May (一对多和一对一原理一样只是换了一个注解)
@Select("查询全部SQL")
@Results({@Result(property = "需要连接的表名", column = "外键", many = @Many(select = "对应的链表带参查询"))})
Department 方法名();
@Select("带参查询")
List<Employee> 方法名(@Param("参数名") Integer 参数名);
public interface DepartmentMapper {
@Select("SELECT * FROM departments")
@Results({
@Result(property = "employees", column = "id", many = @Many(
select = "selectEmployeesByDepartmentId"
))
})
Department getDepartmentWithEmployees();
}
public interface EmployeeMapper {
@Select("SELECT * FROM employees WHERE department_id = #{departmentId}")
List<Employee> selectEmployeesByDepartmentId(@Param("departmentId") Integer departmentId);
}
//实体类
public class Department {
private Integer id;
private String name;
// 省略其他属性和 getter/setter 方法
private List<Employee> employees; // 一对多关联
}
public class Employee {
private Integer id;
private String name;
private Integer departmentId; // 外键
// 省略其他属性和 getter/setter 方法
}
2.4多对多链表查询 (有中间表,如果没有中间表则和一对一、一对多相同)
public interface StudentMapper {
@Select("查询全部")
@Results({
@Result(property = "连接表名", column = "外键", many = @Many(
select = "连接表带参查询方法名"
))
})
Student 方法名();
}
public interface CourseMapper {
@Select("带参查询SQL")
List<Course> 方法名(@Param("外键id") Integer 外键id);
@Select("SELECT * FROM 发起连接表名 WHERE 编号 IN " +
"(SELECT 编号 FROM 中间表 WHERE 被链接表明 = #{外键编号})")
List<Student> 方法名(@Param("外键编号") Integer 外键编号);
}
public interface StudentMapper {
@Select("SELECT * FROM students WHERE id = #{id}")
@Results({
@Result(property = "id", column = "student_id"),
@Result(property = "name", column = "student_name"),
@Result(property = "courses", column = "id", many = @Many(
select = "selectCoursesByStudentId"
))
})
Student getStudentWithCourses(@Param("id") Integer id);
}
public interface CourseMapper {
@Select("SELECT * FROM courses WHERE id = #{courseId}")
List<Course> selectCoursesByStudentId(@Param("courseId") Integer courseId);
@Select("SELECT * FROM students WHERE id IN " +
"(SELECT student_id FROM student_course WHERE course_id = #{courseId})")
List<Student> selectStudentsByCourseId(@Param("courseId") Integer courseId);
}
//实体类
public class Student {
private Integer id;
private String name;
// 省略其他属性和 getter/setter 方法
private List<Course> courses; // 多对多关联
}
public class Course {
private Integer id;
private String title;
// 省略其他属性和 getter/setter 方法
private List<Student> students; // 多对多关联
}
public class StudentCourse {
private Integer studentId;
private Integer courseId;
// 省略其他属性和 getter/setter 方法
}
2.5@Results使用
简介:@Results
注解用于指定一组结果映射规则,通常与 @Select
、@Insert
、@Update
或 @Delete
注解一起使用。这个注解可以包含多个 @Result
注解作为其值,每个 @Result
注解定义了如何将查询结果中的一列或多列映射到实体对象的属性。
2.6@Result使用
简介:他能帮我们把一个实体类成员变量映射数据库字段。出了以下常见属性以外还有:
property
:映射到的 Java 实体类的属性名。column
:数据库表中的列名。javaType
:Java 类型(可选)。jdbcType
:JDBC 类型(可选)。id
:如果结果映射是复合主键的一部分,这个属性设置为true
(可选)
@Results({@Result(property = "实体类成员变量名称", column = "数据库字段名称"),})
2.7@Select如何进行动态SQL
public class Mapper{
@SelectProvider(method = "方法名", type = 动态SQL类.class)
List<JobApplyFor> 方法名();
}
public class 动态SQL类 {
public String 方法名() {
//在这里进行动态SQL拼装即可
return "SQL";
}
}
@Mapper
public interface JobApplyForMapper {
@SelectProvider(method = "selectAll", type = JobApplyForProvider.class)
List<JobApplyFor> selectAll(@Param("jobApplyForCo") JobApplyForCo jobApplyForCo);
}
public class JobApplyForProvider {
public String selectAll(JobApplyForCo jobApplyForCo) {
return "SELECT job_apply_for_id, post_id, department_id, deadline_id, state, apply_for_time, remarks, deadline "
+ "FROM job_apply_for "
+ "ORDER BY apply_for_time " + (jobApplyForCo.getSort() != null ? jobApplyForCo.getSort() : "");
}
}
2.8简单链表查询
可以直接通过写SQL的方式完成链表查询,无需以上麻烦的逻辑。并且只需要标明查询到的字段
@Select("SQL")
@Results({
@Result(property = "被链接表名.被链接表实体类字段",column = "被链接表数据库字段")
})
List<JobApplyFor> selectAll();
@Select("select ap.approval_id, ap.approval_person, ap.approval_date, ap.approval_type, ap.approval_status, ap.application_withdrawn, ap.approval_opinion, al.applicants_name from approval ap inner join applicants al on ap.applicants_id=al.applicants_id")
@Results({
@Result(property = "applicants.applicantsName",column = "applicants_name")
})
List<JobApplyFor> selectAll();
三、@Insert新增进阶使用
3.1@Insert新增返回主键ID并且自增主键
@Options(useGeneratedKeys = true, keyProperty = "实体类Id字段", keyColumn = "数据库Id字段")
四、@Update与@Delete进阶使用
4.177@Update与@Delete删除或修改返回ID
可以通过先查后删的策略获得删除或修改的ID。本身Mybatis并不是JPA无法像JPA那样。除非升级Mybatis-plus可以做到。
使用Mybatis-plus不会影响Mybatis本身结构代码。Mybatis-plus只会在Mybatis基础上只做升级,不做修改。 ---Mybatis-Plus官方说明