MyBatis高级
- MyBatis注解开发
- MyBatis 注解实现多表操作
- MyBatis 构建SQL语句
- MyBatis 学生管理系统
一、MyBatis注解开发
常见注解介绍
-
我们除了可以使用映射配置文件来操作以外,还可以使用注解形式来操作。
-
常用注解
@Select(“查询的SQL语句”):执行查询操作注解
@Insert(“新增的SQL语句”)︰执行新增操作注解
@Update(“修改的SQL语句”)︰执行修改操作注解
@Delete(“删除的SQL语句”)︰执行删除操作注解
注解实现查询操作
- 创建接口和查询方法
- 在核心配置文件中配置映射关系
- 编写测试类心
注意:
注解的方式就省略映射配置文件了
提供一个student
public class Student{
private Integer id:lprivate String name;private Integer age;
public Student(){}
public Student(Integer id,String name,Integer age) {
this.id = id;
this.name = name;this.age = age;
}
注解来自于org.apache.ibatis.annotations 包下的
接口
StudentMapper
public interface StudentMapper{
//查询全部
@Select("select * from student")
public abstract List<Student> selectA11();
}
MyBatisConfig.xml
<?xml version="1.o"encoding="UTF-8"?>
//MyBati 的DTD 约束
<! DOCTYPE mapper PUBLIC"-//mybatis.orgl/DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
// configuration 核心根标签
<configuration>
//引入数据库连接的配置文件
<properties resource ="jdbc.properties">
//配置LOG4J
<settings>
<setting name = "logImpl" value = "log4j" />
</settings>
//起别名
<typeAliases>
<typeAlias type ="com.itheima.bean.Student" alias="student"/>
//<package name="com.itheima.bean"/>
</typeAliases>
//集成分页助手插件
<plugins>
<plugin interceptor ="com.github.pagehelper.PageInterceptor"></plugin>
<plugins>
//environments 配置数据库环境,环境可以有多个 default 属性指定使用的是那个
<environments default="mysql">
// ebvurionment 配置数据库环境 id属性唯一标识
<environment id="mysql">
//transactionManager事务的管理 type属性 采用JDBC 默认的事务
<transactionManager type="JDBC"></transactionManager>
//dataSource 数据源信息 type属性 连接池
<dataSource type="POOLED">
//property 获取数据库连接配置信息
<property name=" driver" value="${driver}">
<property name="url" value=" ${url}”>
<property name="username" value="${username}"/>
<property name=" password" value="${password}”>
</ dataSource>
</ environment>
</environments>
//mappers 配置映射关系
<mappers>
<package name = "com.itheima. mapper"/>
</mappers>
</configuration>
测试
pub1ic class Test02 {
@Test
pub1ic void selectAll() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
List<Student> list = mapper. selectAll() ;
//6.处理结果
for (Student student : list) {
System.out.print1n(student)
}
//7.释放资源
sq1Session .close();
is.close();
}
注解实现新增操作
- 创建新增方法
- 编写测试类
接口
StudentMapper
public interface StudentMapper{
//查询全部
@Select("select * from student")
public abstract List<Student> selectA11();
//新增操作
@Insert("INSERT INTO student VALUES(#{id},#{name},#{age})")
public abstract Integer insert(Student stu);
}
测试
pub1ic class Test02 {
@Test
pub1ic void inisert() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
Student stu = new Student( id: 4,name:"赵六",age: 26);
Integer result = mapper.insert(stu) ;
//6.处理结果
System.out.print1n(result);
//7.释放资源
sq1Session .close();
is.close();
}
注解实现修改操作
- 创建新增方法
- 编写测试类
接口
StudentMapper
public interface StudentMapper{
//查询全部
@Select("select * from student")
public abstract List<Student> selectA11();
//新增操作
@Insert("INSERT INTO student VALUES(#{id},#{name},#{age})")
public abstract Integer insert(Student stu);
}
//修改操作
@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
public abstract Integer update(Student stu);
}
测试
pub1ic class Test02 {
@Test
pub1ic void update() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
Student stu = new Student( id: 4,name:"小七",age: 16);
Integer result = mapper.update(stu) ;
//6.处理结果
System.out.print1n(result);
//7.释放资源
sq1Session .close();
is.close();
}
注解实现删除操作
- 创建新增方法
- 编写测试类
接口
StudentMapper
public interface StudentMapper{
//查询全部
@Select("select * from student")
public abstract List<Student> selectA11();
//新增操作
@Insert("INSERT INTO student VALUES(#{id},#{name},#{age})")
public abstract Integer insert(Student stu);
}
//修改操作
@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
public abstract Integer update(Student stu);
//删除操作
@Delete("DELETE FROM student WHERE id=#{id}")
public abstract Integer delete(Integer id);
}
测试
pub1ic class Test02 {
@Test
pub1ic void delete() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
Integer result = mapper.delete(4);
//6.处理结果
System.out.print1n(result);
//7.释放资源
sq1Session .close();
is.close();
}
注解开发小结
- 注解可以简化开发操作,省略映射配置文件的编写。
- 常用注解
@Select(“查询的SQL语句”):执行查询操作注解
@Insert(“查询的SQL语句”)︰执行新增操作注解
@Update(“查询的SQL语句”)∶执行修改操作注解
@Delete(“查询的SQL语句”)∶执行删除操作注解 - 配置映射关系
< mappers>
< package name="接口所在包" />
</ mappers>
二、MyBatis 注解实现多表操作
一对一
- 环境准备
- @Results :封装映射关系的父注解。
Result[] value():定义了Result数组 - @Result:封装映射关系的子注解。
column属性∶查询出的表中字段名称
property属性:实体对象中的属性名称
javaType属性∶被包含对象的数据类型
one属性:一对一查询固定属性 - @One :一对一查询的注解。
select属性:指定调用某个接口中的方法
CREATE DATABASE db2;
USE db2;
QCREATE TABLE person (
id INT PRIMARY KEY AUTO_ INCREMENT,
NAME VARCHAR (20) ,
age INT
);
INSERT INTO person VALUES (NULL, '张三' ,23) ;
INSERT INTO person VALUES (NULL, '李四' ,24) ;
INSERT INTO person VALUES (NULL, '王五' ,25) ;
CREATE TABLE card (
id INT PRIMARY KEY AUTO_ INCREMENT ,
number VARCHAR(30) ,
pid INT,
CONSTRAINT cp _fk FOREIGN KEY (pid) REFERENCES person (id)
) ;
INSERT INTO card VALUES (NULL, ' 12345' ,1) ;
INSERT INTO card VALUES (NULL, '23456',2) ;
INSERT INTO card VALUES (NULL, '34567',3) ;
Person
@Date
public class Person {
private Integer id; //主键id
private String name; //人的姓名
private Integer age; //人的年龄
pub1ic Person() {
public Person(Integer id, String
name,
,Integer age) {
this. id = id;
this. name = name;
this. age = age;
}
Card
@Date
pub1ic class Card {
private Integer id;/ / /主键id
private String number; //身份证号
private Person p; //所属人的对象
public Card() {
pub1ic Card(Integer id, String number, Person p){
this. id = id;
this. number = number;
this.p = p;
接口
CardMapper
public interface CardMapper{
//查询全部
@Select("SELECT*FROM card")
@Results({
@Result(column = "id" , property = "id"),
@Result(column = "number",property = "number"),
@Result(
property = "p",//被包含象的变量名
javaType = Person.c1ass, //被包含对象的实际数据类型
column ="pid",//根据查询出的card表中的pid字段来查询person表
/*
one、@One 一对一固定写法
select属性:指定调用哪个接口中的哪个方法
*/
one = @0ne(select = "com.itheima.one_to_one.PersonMapper.se1ectById")
})
public abstract List<Card> selectA11();
接口
PersonMapper
public interface PersonMapper{
//根据id查询
@Select("SELECT* FROM person WHERE id=#{id}")
public abstract Person selectById(Integer id);
测试
pub1ic class Test02 {
@Test
pub1ic void delete() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(CardMapper.class);
// 5.调用实现类的方法
List<Card> list = mapper.selectAll();
//6.处理结果
for (Card card : list){
System.out.print1n(result);
}
//7.释放资源
sq1Session .close();
is.close();
}
一对多
- 环境准备
- Results :封装映射关系的父注解。
Result[] value()∶定义了Result数组· - @Result :封装映射关系的子注解。
column属性:查询出的表中字段名称
property属性:实体对象中的属性名称
javaType属性∶被包含对象的数据类型
many属性:一对多查询固定属性 - @Many : 一对多查询的注解。
select属性∶指定调用某个接口中的方法
CREATE TABLE classes (
id INT PRIMARY KEY AUTO_ INCREMENT,
NAME VARCHAR (20) I
);
INSERT INTO classes VALUES (NULL, '黑马一班');
INSERT INTO classes VALUES (NULL, '黑马二班') ;
CREATE TABLE student (
id INT PRIMARY KEY AUTO_ INCREMENT ,
NAME VARCHAR (30),
age INT,
cid INT,
CONSTRAINT Cs_ fk FOREIGN KEY (cid) REFERENCES classes (id)
);
INSERT INTO student VALUES (NULL, '张三' ,23,1);
INSERT INTO student VALUES (NULL, '李四' ,24,1) ;
INSERT INTO student VALUES (NULL, '王五' ,25,2) ;
INSERT INTO student VALUES (NULL, '赵六',26,2) ;
student
@Date
pub1ic c1ass Student {
private Integer id; //主键id
private String name; //学 生姓名
private Integer age; // 学生年龄
public Student() {
}
public Student (Integer id, String name,Integer age){
this. id = id;
this. name = name ;
this. age = age;
}
Clases
@Date
pub1ic c1ass Classes {
private Integer id;//主键id
private String name;, // 班级名称
private List<Student> students; //班级中所有学生对象
public Classes() {
}
public Classes (Integer id, String name,List<Student> students) {
this. id = id;
this. name = name ;
this. students = students;
}
接口
ClassesMapper
public interface ClasesMapper{
//查询全部
@Select("SELECT*FROM classes")
@Results({
@Result(column = "id" , property = "id"),
@Result(column = "name",property = "name"),
@Result(
property = "students",//被包含象的变量名
javaType = List.c1ass, //被包含对象的实际数据类型
column ="id",//根据查询出的classes表中的id字段来查询student表
/*
many、@Many 一对多固定写法
select属性:指定调用哪个接口中的哪个方法
*/
many = @Many (select = "com.itheima.one_to_Many.PersonMapper.se1ectByCid")
})
public abstract List<Classes> selectAl1();
接口
StudentMapper
public interface StudentMapper{
//根据cid查询 student 表
@Select("SELECT* FROM student WHERE cid=#{cid}")
public abstract List<Student> selectByCid(Integer cid);
测试
pub1ic class Test02 {
@Test
pub1ic void selectAll() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(CardMapper.class);
// 5.调用实现类的方法
List<Classes> list = mapper.selectAll();
//6.处理结果
for(Classes cls:list){
System. out. println(c1s.getId() + "," + c1s. getName();
List <Student> siudents .=cls.getStudents();
for (Student student : students)..{
System. out. print1n("\t" +student) ;
}
}
//7.释放资源
sq1Session .close();
is.close();
}
多对多
- 环境准备
- @Results:封装映射关系的父注解。
Result[]value():定义了Result数组 - @Result :封装映射关系的子注解。
column属性∶查询出的表中字段名称
property属性∶实体对象中的属性名称
javaType属性∶被包含对象的数据类型
many属性:一对多查询固定属性 - @Many :一对多查询的注解。
select属性∶指定调用某个接口中的方法
course
CREATE TABLE course (
id INT PRIMARY KEY AUTO_ INCREMENT ,
NAME VARCHAR (20)
);
INSERT INTO course VALUES (NULL, '语文') ;
INSERT INTO course VALUES (NULL, '数学') ;
stu_cr
CREATE TABLE stu_cr (
id INT PRIMARY KEY AUTO_ INCREMENT,
sid INT,
cid INT,
CONSTRAINT sc_fk1 FOREIGN KEY (sid) REFERENCES student (id),
CONSTRAINT sc_fk2 FOREIGN KEY (cid) REFERENCES course (id)
);
INSERT INTO stu_cr VALUES (NULL, 1,1) ;
INSERT INTO stu_cr VALUES (NULL, 1,2) ;
INSERT INTO stu_cr VALUES (NULL, 2,1) ;
INSERT INTO stu_cr VALUES (NULL, 2,1) ;
student
CREATE TABLE student (
id INT PRIMARY KEY AUTO_ INCREMENT ,
NAME VARCHAR (30),
age INT,
cid INT,
CONSTRAINT Cs_ fk FOREIGN KEY (cid) REFERENCES classes (id)
);
INSERT INTO student VALUES (NULL, '张三' ,23,1);
INSERT INTO student VALUES (NULL, '李四' ,24,1) ;
INSERT INTO student VALUES (NULL, '王五' ,25,2) ;
INSERT INTO student VALUES (NULL, '赵六',26,2) ;
Course
@Date
public class Course {
private Integer id;//主键id
private String name; //课程名称
public Course() {
public Course (Integer id, String name) {
this.id = id;
this. name = name;
}
Student
@Date
pub1ic c1ass Student {
private Integer id; //主键id
private String name; //学 生姓名
private Integer age; // 学生年龄
private List<Course> courses; //学生所选择课程集合
public Student() {
}
public Student(Integer id,String name, Integer age,List<Course> courses){
this. id = id;
this. name = name;
this. age = age;
this. courses = courses;
}
接口
StudentMapper
public interface StudentMapper{
//查询全部
@Select("SELECT DISTINCT s.id,s.name,s.age FROM student s, stu_cr sc WHERE sc.sid=s.id")
@Results({
@Result(column = "id" , property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "age",property = "age"),
@Result(
property = "courses",//被包含象的变量名
javaType = List.c1ass, //被包含对象的实际数据类型
column = "id",//根据查询出的classes表中的id字段来查询student表
/*
many、@Many 一对多固定写法
select属性:指定调用哪个接口中的哪个方法
*/
many = @Many (select = "com.itheima.many_to_Many.PersonMapper.se1ectBySid")
})
public abstract List<Student> selectAll();
接口
CourseMapper
public interface CourseMapper{
//根据学生id查询所选课程
@Select("SELECT c.id, c.name FROM stu_cr sc, course c WHERE sc.cid=c.id AND sc.sid=#{id}")
public abstract List Course> selectBySid(Integer id) ;
测试
pub1ic class Test02 {
@Test
pub1ic void selectAll() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(CardMapper.class);
// 5.调用实现类的方法
List<Student> list = mapper.selectAll();
//6.处理结果
for (Student student : list){
System.out.println(student.getId() + "," + student.getName()+ "," + student.getAge());
List<Course> courses = student.getCourses();
for (Course cours : courses){
System.out. print1n("\t" +cours);
}
}
//7.释放资源
sq1Session .close();
is.close();
}
注解多表操作小结
- @Results :封装映射关系的父注解。
Result[] value():定义了Result数组 - @Result :封装映射关系的子注解。
column属性∶查询出的表中字段名称
property属性:实体对象中的属性名称
javaType属性∶被包含对象的数据类型
one属性:一对一查询固定属性
many属性:一对多查询固定属性 - @One :一对一查询的注解。
select属性:指定调用某个接口中的方法 - @Many :一对多查询的注解。
select属性:指定调用某个接口中的方法
三、MyBatis 构建SQL语句
SQL 构建对象介绍
- 我们之前通过注解开发时,相关SQL语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。
- MyBatis给我们提供了org.apache.ibatis.jdbc.SQL功能类,专门用于构建SQL语句。
查询操作
- 定义功能类并提供获取查询的SQL语句的方法。
- @SelectProvider:生成查询用的SQL语句注解。
type属性∶生成SQL语句功能类对象
method属性∶指定调用方法
ReturnSql
pub1ic class ReturnSql {
//定义方法,返回查询的sql语句
public String getSelectAll(){
return new sQL(){
{
SELECT( columns: " * ");
FROM( " student") ;
}
}.toString() ;
}
}
StudentMapper
pub1ic interface StudentMapper {
//查询全部
//@Select("SELECT*FROM student")
@SelectProvider(type = ReturnSql.class,method = "getselectA11")
public abstract List<Student> selectA11();
//新增功能
@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
public abstract Integer insert(Student stu);
//修改功能
@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
public abstract Integer update(Student stu);
//删除功能
@Delete("DELETE FROM student WHERE id={id}")
public abstract Integer delete(Integer id) ;
测试
pub1ic class Test02 {
@Test
pub1ic void selectAll() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
List<Student> list = mapper. selectAll() ;
//6.处理结果
for (Student student : list) {
System.out.print1n(student)
}
//7.释放资源
sq1Session .close();
is.close();
}
新增操作
- 定义功能类并提供获取查询的SQL语句的方法。
- @InsertProvider:生成查询用的SQL语句注解。
type属性∶生成SQL语句功能类对象
method属性∶指定调用方法
ReturnSql
pub1ic class ReturnSql {
//定义方法,返回查询的sql语句
public String getSelectAll(){
return new sQL(){
{
SELECT( columns: " * ");
FROM( " student") ;
}
}.toString() ;
)
//定义方法,返回新增的sql语句
pub1ic String getInsert(Student stu) {
return new sQL() {
{
INSERT_INTO("student");
INTO_VALUES("#{id},#{name},#{age}");
}
}.toString() ;
}
}
StudentMapper
pub1ic interface StudentMapper {
//查询全部
//@Select("SELECT*FROM student")
@SelectProvider(type = ReturnSql.class,method = "getselectA11")
public abstract List<Student> selectA11();
//新增功能
//@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
@InsertProvider(type = ReturnSql.class , method = "getInsert")
public abstract Integer insert(Student stu);
//修改功能
@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
public abstract Integer update(Student stu);
//删除功能
@Delete("DELETE FROM student WHERE id={id}")
public abstract Integer delete(Integer id) ;
测试
pub1ic class Test02 {
@Test
pub1ic void inisert() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
Student stu = new Student( id: 4,name:"赵六",age: 26);
Integer result = mapper.insert(stu) ;
//6.处理结果
System.out.print1n(result);
//7.释放资源
sq1Session .close();
is.close();
}
修改操作
- 定义功能类并提供获取查询的SQL语句的方法。
- @UpdateProvider:生成查询用的SQL语句注解。
type属性∶生成SQL语句功能类对象
method属性∶指定调用方法
ReturnSql
pub1ic class ReturnSql {
//定义方法,返回查询的sql语句
public String getSelectAll(){
return new sQL(){
{
SELECT( columns: " * ");
FROM( " student") ;
}
}.toString() ;
)
//定义方法,返回新增的sql语句
pub1ic String getInsert(Student stu) {
return new sQL() {
{
INSERT_INTO("student");
INTO_VALUES("#{id},#{name},#{age}");
}
}.toString() ;
}
//定义方法,返回修改的sql语句
pub1ic String getUpdate(Student stu) {
return new sQL() {
{
UPDATE("student");
SET("name = #{name}","age = #{age}");
WHERE("id=#{id}");
}
}.toString() ;
}
}
StudentMapper
pub1ic interface StudentMapper {
//查询全部
//@Select("SELECT*FROM student")
@SelectProvider(type = ReturnSql.class,method = "getselectA11")
public abstract List<Student> selectA11();
//新增功能
//@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
@InsertProvider(type = ReturnSql.class , method = "getInsert")
public abstract Integer insert(Student stu);
//修改功能
//@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
@UpdateProvider(type = ReturnSql.class,method ="getUpdate")
public abstract Integer update(Student stu);
//删除功能
@Delete("DELETE FROM student WHERE id={id}")
public abstract Integer delete(Integer id) ;
测试
pub1ic class Test02 {
@Test
pub1ic void update() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
Student stu = new Student( id: 4,name:"小七",age: 16);
Integer result = mapper.update(stu) ;
//6.处理结果
System.out.print1n(result);
//7.释放资源
sq1Session .close();
is.close();
}
删除操作
- 定义功能类并提供获取查询的SQL语句的方法。
- @DeleteProvider:生成查询用的SQL语句注解。
type属性∶生成SQL语句功能类对象
method属性∶指定调用方法
ReturnSql
pub1ic class ReturnSql {
//定义方法,返回查询的sql语句
public String getSelectAll(){
return new sQL(){
{
SELECT( columns: " * ");
FROM( " student") ;
}
}.toString() ;
)
//定义方法,返回新增的sql语句
pub1ic String getInsert(Student stu) {
return new sQL() {
{
INSERT_INTO("student");
INTO_VALUES("#{id},#{name},#{age}");
}
}.toString() ;
}
//定义方法,返回修改的sql语句
pub1ic String getUpdate(Student stu) {
return new sQL() {
{
UPDATE("student");
SET("name = #{name}","age = #{age}");
WHERE("id=#{id}");
}
}.toString() ;
}
//定义方法,返回删除的sql语句
pub1ic String getDelete(Student stu) {
return new sQL() {
{
DELETE_FROM("student");
WHERE("id=#{id}");
}
}.toString() ;
}
}
StudentMapper
pub1ic interface StudentMapper {
//查询全部
//@Select("SELECT*FROM student")
@SelectProvider(type = ReturnSql.class,method = "getselectA11")
public abstract List<Student> selectA11();
//新增功能
//@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
@InsertProvider(type = ReturnSql.class , method = "getInsert")
public abstract Integer insert(Student stu);
//修改功能
//@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
@UpdateProvider(type = ReturnSql.class,method ="getUpdate")
public abstract Integer update(Student stu);
//删除功能
@Delete("DELETE FROM student WHERE id={id}")
@DeleteProvider(type = ReturnSql.class,method ="getDelete")
public abstract Integer delete(Integer id) ;
测试
pub1ic class Test02 {
@Test
pub1ic void delete() throws Exception{
// 1.加载核心配置文件
InputStream is = Resources. getResourceAsStream(”MyBatisConfig. xm1”) ;
//2.获取SqlSession 工厂对象
Sq1SessionFactory sqlSessionFactory = new Sq1SessionFactoryBui1der (). build(is) ;
//3.通过工厂对象获取SqlSession 对象
Sq1Session sq1Session = sq1SessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sq1Session.getMapper(StudentMapper.class);
// 5.调用实现类的方法
Integer result = mapper.delete(4);
//6.处理结果
System.out.print1n(result);
//7.释放资源
sq1Session .close();
is.close();
}
构建SQL语句小结
- org.apache.ibatis.jdbc.SQL:构建SQL语句的功能类。通过一些方法来代替SQL语句的关键字。
SELECT(
FROM()
WHERE()
INSERT_INTO()
VALUES()
UPDATE(
DELETE_FROM) - @SelectProvider :生成查询用的SQL语句注解。
- @lnsertProvider :生成新增用的SQL语句注解。
- @UpdateProvider:生成修改用的SQL语句注解。
- @DeleteProvider:生成删除用的SQL语句注解。
type属性∶生成SQL语句功能类对象
method属性∶指定调用方法