
本文共 15685 字,大约阅读时间需要 52 分钟。
Mybatis高级
1.MyBtis注解开发
1.1 常用注解介绍
我们除了可以使用映射配置文件来操作以外,还可以使用注解形式来操作
常用注解:
- @Select(“查询的SQL语句”):执行查询操作注解
- @Insert(“新增的SQL语句”):执行新增操作注解
- @Update(“修改的SQL语句”):执行修改操作注解
- @Delete(“删除的SQL语句”):执行删除操作注解
1.2 注解实现查询操作
创建接口和查询方法
public interface StudentMapper { //查询全部 @Select("select * from student") public ListselectAll();}
在核心配置文件中配置映射关系
编写测试类
@Testpublic void selectAll() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist = mapper.selectAll(); //6.处理结果 for (Student student : list) { System.out.println(student); } //7.释放资源 sqlSession.close(); is.close();}
1.3 注解实现新增操作
创建新增方法
//新增操作 @Insert("insert into student values(#{id},#{name},#{age})") public Integer insert(Student student);
编写测试类
@Testpublic void insert() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Student student = new Student(9,"汤姆",30); Integer resoult = mapper.insert(student); //6.处理结果 System.out.println(resoult); //7.释放资源 sqlSession.close(); is.close();}
1.4 注解实现修改操作
创建新增方法
//修改操作@Update("update student set name = #{name}, age = #{age} where id = #{id}")public Integer update(Student student);
编写测试类
@Testpublic void update() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Student student = new Student(6,"孙悟空",72); Integer resoult = mapper.update(student); //6.处理结果 System.out.println(resoult); //7.释放资源 sqlSession.close(); is.close();}
1.5 注解实现删除操作
创建删除方法
//删除操作@Delete("delete from student where id = #{id}")public Integer delete(Integer id);
编写测试类
@Testpublic void delete() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Integer resoult = mapper.delete(7); //6.处理结果 System.out.println(resoult); //7.释放资源 sqlSession.close(); is.close();}
2.MyBatis注解实现多表操作
2.1 一对一
环境介绍:使用前面的(人与身份证)Person类和Card类
@Results:封装映射关系的父注解
- Result[] value():定义了Result数组
@Result:封装映射关系的子注解
- column属性:查询出的表中字段名称
- property属性:实体对象中的属性名称
- javaType属性:被包含对象的数据类型
- one属性:一对一查询固定属性
@One:一对一查询的注解
- select属性:指定调用某个接口中的方法
核心配置文件:配置映射关系
接口PersonMapper:
public interface PersonMapper { //根据id查询 @Select("select * from person where id = #{id}") public Person selectById(Integer id);}
接口CardMapper:
public interface CardMapper { //查询全部 @Select("select * from card") @Results({ @Result(column = "id", property="id"), @Result(column = "number", property = "number"), @Result( property = "p", //被包含对象的变量名 javaType = Person.class, //被包含对象的实际数据类型 column = "pid", //根据查询出的card表中的pid字段来查询person表 /* one、@One 一对一固定写法 select属性:指定调用哪个接口中的哪个方法 */ one = @One(select = "cn.itcast.one_to_one.PersonMapper.selectById") ) }) public ListselectAll();}
测试类:
@Testpublic void selectAll() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取CardMapper接口的实现类对象 CardMapper mapper = sqlSession.getMapper(CardMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist = mapper.selectAll(); //6.处理结果 for (Card card : list) { System.out.println(card); } //7.释放资源 sqlSession.close(); is.close();}
测试运行结果:
Card{id=1, number=‘123456’, p=Person{id=1, name=‘张三’, age=23}}
Card{id=2, number=‘223456’, p=Person{id=2, name=‘李四’, age=24}} Card{id=3, number=‘323456’, p=Person{id=3, name=‘王五’, age=25}}2.2 一对多
环境介绍:使用前面的(班级与学生)Classes类和Student类
@Results:封装映射关系的父注解
- Result[] value():定义了Result数组
@Result:封装映射关系的子注解
- column属性:查询出的表中字段名称
- property属性:实体对象中的属性名称
- javaType属性:被包含对象的数据类型
- many属性:一对多查询固定属性
@Many:一对多查询的注解
- select属性:指定调用某个接口中的方法
核心配置文件:配置映射关系(由于一对一和一对多都需要使用该配置文件,所以需要后退一级)
接口:StudentMapper
public interface StudentMapper { //根据id查询 @Select("select * from student where cid = #{id}") public ListselectById(Integer id);}
接口:ClassesMapper
public interface ClassesMapper { //查询全部 @Select("select * from classes") @Results({ @Result(column = "id", property = "id"), @Result(column = "name", property = "name"), @Result( property = "students", //被包含对象的变量名 javaType = List.class, //被包含对象的实际数据类型 column = "id", //根据查询出的classes表的id字段来查询student表 /* many、@Many 一对多查询的固定写法 select属性:指定调用哪个接口中的哪个方法 */ many = @Many(select = "cn.itcast.one_to_many.StudentMapper.selectById") ) }) public ListselectAll();}
测试类:
@Testpublic void selectAll() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取ClassesMapper接口的实现类对象 ClassesMapper mapper = sqlSession.getMapper(ClassesMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist = mapper.selectAll(); //6.处理结果 for (Classes cls : list) { System.out.println(cls.getId()+","+cls.getName()); List students = cls.getStudents(); for (Student student : students) { System.out.println("\t"+student); } } //7.释放资源 sqlSession.close(); is.close();}
测试运行结果:
1,一班
Student{id=1, name=‘张三’, age=23} Student{id=2, name=‘李四’, age=24} 2,二班 Student{id=3, name=‘王五’, age=25} Student{id=4, name=‘赵六’, age=26}2.3 多对多
环境介绍:使用前面的(班级与学生)Classes类和Student类
@Results:封装映射关系的父注解
- Result[] value():定义了Result数组
@Result:封装映射关系的子注解
- column属性:查询出的表中字段名称
- property属性:实体对象中的属性名称
- javaType属性:被包含对象的数据类型
- many属性:一对多查询固定属性
@Many:一对多查询的注解
- select属性:指定调用某个接口中的方法
核心配置文件:配置映射关系
接口:CourseMapper
public interface CourseMapper { //根据id查询 @Select("select c.id,c.name from course c,stu_cr sc where c.id = sc.cid and sc.sid = #{sid}") public ListselectBySid(Integer sid);}
接口:StudentMapper
public interface StudentMapper { //查询全部 @Select("select distinct s.id,s.name,s.age from student s,stu_cr sc where s.id = sc.sid") @Results({ @Result(column = "id", property = "id"), @Result(column = "name", property = "name"), @Result(column = "age", property = "age"), @Result( property = "courses", javaType = List.class, column = "id", /* many、@Many 一对多查询的固定写法 select属性:指定调用哪个接口中的哪个方法 */ many = @Many(select = "cn.itcast.many_to_many.CourseMapper.selectBySid") ) }) public ListselectAll();}
测试类:
@Testpublic void selectAll() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取ClassesMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist = mapper.selectAll(); //6.处理结果 for (Student stu : list) { System.out.println(stu.getId()+","+stu.getName()+","+stu.getAge()); List students = stu.getCourses(); for (Course course : students) { System.out.println("\t"+course); } } //7.释放资源 sqlSession.close(); is.close();}
测试运行结果:
1,张三,23
Course{id=1, name=‘语文’} Course{id=2, name=‘数学’} 2,李四,24 Course{id=1, name=‘语文’} Course{id=2, name=‘数学’}3.MyBatis构建sql语句
3.1 SQL构建对象介绍
我们之前通过注解开发时,相关SQL语句都是自己直接拼写的。一些关键字写起来比较麻烦,而且容易出错。
MyBatis给我们提供了org.apache.ibatis.jdbc.SQL功能类,专门用于构建SQL语句。
方法名 | 说明 |
---|---|
SELECT(String…column) | 根据字段拼接查询语句 |
FROM(String…table) | 根据表名拼接语句 |
WHERE(String…condition) | 根据条件拼接语句 |
INSERT_INTO(String table) | 根据表名拼接新增语句 |
VALUES(String column,String values) | 根据字段和值拼接插入数据语句 |
UPDATE(String table) | 根据表名拼接修改语句 |
DELETE_FROM(String table) | 根据表名拼接删除语句 |
… | … |
public class SqlTest { public static void main(String[] args) { String sql = getSelectSql(); System.out.println(sql); } //定义方法,获取查询student表的sql语句// public static String getSelectSql(){ // String sql = "select * from student";// return sql;// } public static String getSelectSql(){ return new SQL(){ { SELECT("*"); FROM("student"); } }.toString(); }}
3.2 查询操作
定义功能类并提供获取查询SQL语句的方法
@SelectProvider:生成查询用的SQL语句注解
- type属性:生成SQL语句功能类对象
- method属性:指定调用方法
获取SQL语句的功能类:
public class ReturnSql { //定义方法,返回查询的sql语句 public static String getSelectAll() { return new SQL() { { SELECT("*"); FROM("student"); } }.toString(); }}
接口:StudentMapper
public interface StudentMapper { //查询全部// @Select("select * from student") @SelectProvider(type = ReturnSql.class, method = "getSelectAll") public ListselectAll(); //新增操作 @Insert("insert into student values(#{id},#{name},#{age})") public Integer insert(Student student); //修改操作 @Update("update student set name = #{name}, age = #{age} where id = #{id}") public Integer update(Student student); //删除操作 @Delete("delete from student where id = #{id}") public Integer delete(Integer id);}
测试查询功能:
@Testpublic void selectAll() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist = mapper.selectAll(); //6.处理结果 for (Student stu : list) { System.out.println(stu); } //7.释放资源 sqlSession.close(); is.close();}
测试运行结果:
Student{id=1, name=‘张三’, age=23}
Student{id=2, name=‘李四’, age=24} Student{id=3, name=‘王五’, age=25} Student{id=4, name=‘赵六’, age=26}3.2 新增操作
定义功能类并提供获取新增SQL语句的方法
@InsertProvider:生成新增用的SQL语句注解
- type属性:生成SQL语句功能类对象
- method属性:指定调用方法
获取SQL语句的功能类:
//定义方法,返回新增的sql语句public static String getInsert(Student stu) { return new SQL() { { INSERT_INTO("student"); INTO_VALUES("#{id},#{name},#{age}"); } }.toString();}
接口:StudentMapper
//新增操作// @Insert("insert into student values(#{id},#{name},#{age})") @InsertProvider(type = ReturnSql.class, method = "getInsert") public Integer insert(Student student);
测试新增功能:
@Testpublic void insert() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Student stu = new Student(7,"mary",35); Integer result = mapper.insert(stu); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close();}
3.3 修改操作
定义功能类并提供获取修改SQL语句的方法
@UpdateProvider:生成修改用的SQL语句注解
- type属性:生成SQL语句功能类对象
- method属性:指定调用方法
获取SQL语句的功能类:
//定义方法,返回修改的sql语句public static String getUpdate(Student stu) { return new SQL() { { UPDATE("student"); SET("name = #{name}","age = #{age}"); WHERE("id = #{id}"); } }.toString();}
接口:StudentMapper
//修改操作// @Update("update student set name = #{name}, age = #{age} where id = #{id}") @UpdateProvider(type = ReturnSql.class, method = "getUpdate") public Integer update(Student student);
测试修改功能:
@Testpublic void update() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Student stu = new Student(7,"mary",30); Integer result = mapper.update(stu); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close();}
3.4 删除操作
定义功能类并提供获取删除SQL语句的方法
@DeleteProvider:生成删除用的SQL语句注解
- type属性:生成SQL语句功能类对象
- method属性:指定调用方法
获取SQL语句的功能类:
//定义方法,返回删除的sql语句public static String getDelete(Integer id) { return new SQL() { { DELETE_FROM("student"); WHERE("id = #{id}"); } }.toString();}
接口:StudentMapper
//删除操作// @Delete("delete from student where id = #{id}") @DeleteProvider(type = ReturnSql.class, method = "getDelete") public Integer delete(Integer id);
测试修改功能:
@Testpublic void delete() throws IOException { //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Integer result = mapper.delete(9); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close();}
相关文章:、
发表评论
最新留言
关于作者
